简体   繁体   中英

jQuery: Adding “callback” Parameter for JSONP Doesn't Trigger Callbacks

The following piece of code, which calls a service using jQuery's getJSON, without the useJsonp section, worked fine for me for a long time. Then, there was a need to support JSONP and the if (useJsonp) condition was added. This also works fine, until the HTTP request fails. When I'm failing it (using Fiddler) with an 404 response, none of the callback ( .done nor .fail is being called). When the request doesn't fail, I get to the .done callback.

function getData(url){
    var dfd = $.Deferred();
    if (useJsonp) {
        url += '&callback=?';
    }
    $.when($.getJSON(url))
        .done(function (dataObj) {
            if (!dataObj || dataObj.Status === 'failed') {
                dfd.reject(dataObj);
            }
            else {
                doSomething(dataObj);
                dfd.resolve(dataObj);
            }
        })
        .fail(function (jqXHR) {
            dfd.reject(jqXHR);
        });
    return dfd.promise();
};

Why is that? What can I do to make the callbacks called?

Thanks

$.when closing bracket is mising, is it because of that, please try,other code is by far correct. This it the way it is to be achieved.

var dfd = $.Deferred();
if (useJsonp) {
    url += '&callback=?';
}
$.when($.getJSON(url))
    .done(function (dataObj) {
        dfd.resolve(dataObj);
    })
    .fail(function (jqXHR) {
        dfd.reject(jqXHR);
    }));
return dfd.promise();

For jsonp requests I do the following:

$.ajax(url, {
    dataType: useJsonp ? "jsonp" : undefined,
    success: function(result) {
        console.log(result);
        alert("It worked!");
    },
    error: function(result) {
        console.log(result);
        alert("It didn't work!");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM