简体   繁体   English

jQuery:为JSONP添加“回调”参数不会触发回调

[英]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. 下面的代码使用jQuery的getJSON调用服务,而没有useJsonp部分,对我来说很长一段时间都很好。 Then, there was a need to support JSONP and the if (useJsonp) condition was added. 然后,需要支持JSONP并添加了if (useJsonp)条件。 This also works fine, until the HTTP request fails. 这也可以正常工作,直到HTTP请求失败为止。 When I'm failing it (using Fiddler) with an 404 response, none of the callback ( .done nor .fail is being called). 当我使用404响应使它失败(使用Fiddler)时,没有回调( .done.fail被调用)。 When the request doesn't fail, I get to the .done callback. 当请求没有失败时,我进入.done回调。

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: 对于jsonp请求,请执行以下操作:

$.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!");
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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