JQuery - $.ajax() - Cross-origin using JSONP - Get

2019-06-23 15:31发布

问题:

I've the following code to do a crossdomain request and get JSONP data (JSON wrapped with by callback method). I've verified that I'm getting the response correctly with the callback method wrapping my JSON data. It is working PERFECTLY in IE7 (the callback cb is getting called) but not in IE8.

    $(document).ready(function () {
    var abc = $.ajax({
        type: "GET",
        url: "http://sd.domain.com/param1=a&param2=b&output=json&callback=cb",
        dataType: "jsonp",
        jsonp: false,
        cache: false,
        success: function (json) {

        },
        error: function (e) {

        }
    });

    abc.error(function (data, xhr, dat1) {

    });

    abc.complete(function (xhr, status) {
        var data = xhr.responseText;
    });
});

function cb(dd) {
    alert(dd.people[0].nameFirst);
}

I'm getting the statusText as 'Success' and StatusCode as 200 in xhr. Also I'm not able to find any propertly called responseText for xhr. So how can I get the response in the error/complete functions? Any ideas?

回答1:

Jquery automatic pass a callback something like callback=JQuery132123412415235 and the server must return a script calling this function with the data JQuery132123412415235(data_returned) and the rest is equal to the standard json request

You also use the success and error properties and use the promise and error(function (data) ) and complete(function (data)) just for a clear code I think you must use only one method. The code is like this:

$(document).ready(function () {
    var abc = $.ajax({
        type: "GET",
        url: "http://sd.domain.com/param1=a&param2=b&output=json",
        dataType: "jsonp",
        jsonp: false,
        cache: false
    });

    abc.error(function (data, xhr, dat1) {

    });

    abc.complete(function (xhr, status) {
        var data = xhr.responseText;
    });

    abc.done(data){
       //alert(data.people[0].nameFirst); ?????        
    }

});

Remember the server must return the data in the form callback_function(data) where data is the json object like if you returned in a standard json call.