jQuery jsonp 捕获 "Failed to load resources…"
jQuery jsonp catch "Failed to load resources…"
我有一个 Javascript 函数,可以通过 JSONP 从我的服务器获取数据。我试图模拟服务器错误或无法访问互联网(它应该在 cordova 应用程序中 运行,因此客户端可能无法访问互联网),但我无法捕获错误。这是我的代码:
var completed = false;
jQuery.ajax({
url: "http://www.someDomainThatDoesn'tWork.com/getsContent.php?callback=?",
dataType: "json",
success: function(data) {
completed = true
console.log(data);
},
error: function() {
console.log("fail");
},
statusCode: {
404: function() {
console.log("fail 2");
}
}
}).fail(function() {
console.log("fail 3");
}).always(function() {
if (!completed) {
console.log("fail 4");
}
});
如您所见,我尝试在四个地方捕获(不同的)错误。但是,例如,如果我将 url 编辑为一个不存在的,javascript 就会中止并给我错误
Failed to load resource: the server responded with a status of 404 (Not Found)
和 none 的错误捕获器被执行。
在 jQuery.ajax() 的文档中说
Note: This handler is not called for cross-domain script and cross-domain JSONP requests.
so I guess I shouldn't be surprised.
有什么办法可以捕捉到这个错误吗?我也尝试过用
拥抱它
try{} catch(error) {}
但这也无济于事。
因为 JSONP 方法 returns 一个脚本它可能会静默失败,您可能需要将服务器更改为使用 CORS 而不是使用 JSONP 以便能够获得正确的错误处理。
我有一个 Javascript 函数,可以通过 JSONP 从我的服务器获取数据。我试图模拟服务器错误或无法访问互联网(它应该在 cordova 应用程序中 运行,因此客户端可能无法访问互联网),但我无法捕获错误。这是我的代码:
var completed = false;
jQuery.ajax({
url: "http://www.someDomainThatDoesn'tWork.com/getsContent.php?callback=?",
dataType: "json",
success: function(data) {
completed = true
console.log(data);
},
error: function() {
console.log("fail");
},
statusCode: {
404: function() {
console.log("fail 2");
}
}
}).fail(function() {
console.log("fail 3");
}).always(function() {
if (!completed) {
console.log("fail 4");
}
});
如您所见,我尝试在四个地方捕获(不同的)错误。但是,例如,如果我将 url 编辑为一个不存在的,javascript 就会中止并给我错误
Failed to load resource: the server responded with a status of 404 (Not Found)
和 none 的错误捕获器被执行。
在 jQuery.ajax() 的文档中说
Note: This handler is not called for cross-domain script and cross-domain JSONP requests. so I guess I shouldn't be surprised.
有什么办法可以捕捉到这个错误吗?我也尝试过用
拥抱它try{} catch(error) {}
但这也无济于事。
因为 JSONP 方法 returns 一个脚本它可能会静默失败,您可能需要将服务器更改为使用 CORS 而不是使用 JSONP 以便能够获得正确的错误处理。