且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery.ajax - 总是()并不总是运行

更新时间:2022-04-15 22:27:10

这是著名的JSONP调用的东西。按照 $就参考错误

This is something that is known for JSONP calls. According to the $.ajax reference for error:

注:此处理程序不叫跨域脚本和跨域JSONP请求

Note: This handler is not called for cross-domain script and cross-domain JSONP requests.

另外请注意,不支持同步JSONP调用:

Also note that synchronous JSONP calls are not supported:

跨域请求和数据类型:JSONP请求不支持同步操作

Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

解决方法通常包括两种1)设置超时通话或2)使用插件来添加更多的典型错误的功能。

Workarounds typically involve either 1) setting a timeout for the call or 2) using a plugin to add more typical error functionality.

1)设置超时时间(和异步真)

1) Setting a timeout (and async true)

var jqXHR = jQuery.ajax({
    type: 'GET',
    async: true,
    cache: false,
    url: 'http://ip.jsontest.com.BADURL/',
    contentType: 'application/json; charset=UTF-8',
    crossDomain: true,
    dataType: 'jsonp',
    timeout: 2000
})
.fail(function (jqXHR, textStatus, errorThrown) {
    console.log('fail was called');
})
.done(function (data, textStatus, jqXHR) {
    console.log('Your IP is ' + data.ip);
    console.log('done was called');
})
.always(function (dataOrjqXHR, textStatus, jqXHRorErrorThrown) { console.log('always was called'); });

2) jQuery的JSONP插件它增加了差错恢复功能。

2) The jQuery JSONP plugin which adds error recovery features.