我正在使用 jQuery.getJSON()
在可能不存在的 URL(不同域)上。有没有办法让我捕捉到错误“加载资源失败”?由于此调用的异步性质,try/catch 似乎不起作用。
我不能使用 jQuery.ajax()
的“错误:
”。来自文档:
Note: This handler is not called for cross-domain script and JSONP requests.
最佳答案
如果您知道从远程服务返回成功结果的最坏情况延迟,您可以使用超时机制来确定是否有错误。
var cbSuccess = false;
$.ajax({
url: 'http://example.com/.../service.php?callback=?',
type: 'get',
dataType: 'json',
success: function(data) {
cbSuccess = true;
}
});
setTimeout(function(){
if(!cbSuccess) { alert("failed"); }
}, 2000); // assuming 2sec is the max wait time for results
关于javascript - 在跨域请求中捕获 JSONP 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4924434/