Search code examples
jquerygetjson

$.getJSON cant handle named function?


why jquery doesnt executed the function when i name the callback function?

$.getJSON("http://ip.jsontest.com/?callback=showMyIP"),function (){
     console.log("test");}

dev tools shows that i get a correct json

showMyIP({"ip": "84.113.30.7"});

but he simple ignores the following function

if i replace showMyIP with ? and make it anonmyous it works.

also i have a another json which is 100% correct, where jquery refuses to run the anonymous function despite getting a correct json back wrapped in a anony. function, where in debugging i get a missing ; error on some Object which makes no sense at all to me, since there are no ; used in jsons.


Solution

  • You have two problems. First there's a random ) in your code causing a syntax error.

    Secondly, $.getJSON expects a JSON response, not JSONP. To do what you want use $.ajax() and set the correct dataType:

    $.ajax({
      url: 'http://ip.jsontest.com/',
      dataType: 'jsonp',
      jsonpCallback: 'showMyIP',
      success: function(data) {
        console.log(data);
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>