callback function doesn't work when using getJSON function in jQuery

后端 未结 8 1909
心在旅途
心在旅途 2021-01-01 15:59

I am trying to use the getJSON function in jQuery to import some data and trigger a callback function. The callback function doesn\'t run. However, if I try the same thing w

相关标签:
8条回答
  • 2021-01-01 17:03

    As mentioned by numerous others, you need valid JSON (i.e. complies with the rules at http://json.org/) for getJSON to work (this means you cannot get HTML via getJSON as in your example).

    The reason the last test works is because the last parameter "json" is not being interpreted as the "type". Because the following does NOT work:

    $("#test3").click(function() {
        $.get("index.html",
            '',
            function(response) {
                    alert('hi');
                    //works
            },
            "json"
        )
    });
    
    0 讨论(0)
  • 2021-01-01 17:03

    I had the same issue despite having well formed JSON etc. I was able to query my webservice, and get a response, however, my callback function wasn't firing. After scrounging the net, i most interwebers suggested using 'jsonp', which i did since my app performs some cross domain calls, and also added 'callback?' to my url. This didn't work but that including the callback with the returned JSON solved my problem. The code below explains what i mean:

    //server side json formed somewhere up here
    String data = callback + "("+ json +")" ;
    

    the response resulting from this is something like "jsonp1280403476086([{"Name":"Jack Sparrow" which jQuery seemed to not have a problem and so never died on me.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题