如何抓住jQuery AJAX错误? [英] How can I catch jQuery AJAX errors?
问题描述
当一个AJAX请求被提交到一个站点时,服务器端的错误很容易用jQuery promise方法来处理。 .done()
, .fail()
等。但是对于某些请求(例如,到一个无效的站点或一个不接受跨源请求),在进行呼叫时立即发生异常。以下是控制台中一个错误的示例:
When an AJAX request is submitted to a site, server-side errors are easily handled with the jQuery promise approach. .done()
, .fail()
, etc. However for some requests (e.g. to an invalid site or one that doesn't accept cross-origin requests), an exception occurs immediately as the call is made. Here's an example of one error in the console:
XMLHttpRequest无法加载
http:// someotherserver / api / blahblah
。起始
http:// localhost:52625
不允许Access-Control-Allow-Origin。
XMLHttpRequest cannot load
http://someotherserver/api/blahblah
. Originhttp://localhost:52625
is not allowed by Access-Control-Allow-Origin.
是的,我知道CORS ...这不是问题。我正在做的是尝试网络api调用来测试服务器IP /名称是否正确
Yes, I know about CORS...that's not the issue. What I'm actually doing is trying a web api call to test if the server IP/name is correct
我知道错误在jQuery请求语法中
选项:
$.ajax({
url: remoteURL,
type: 'GET',
error: function (err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).etc.etc.
这里处理错误,但是控制台中仍然记录了异常。在 try-catch
块中包含上述内容似乎是合理的,但似乎没有帮助。
The error is handled here, but exceptions are still logged in the console. It seemed reasonable to wrap the above in a try-catch
block, but that doesn't seem to help.
我发现这个问题,但解决方案涉及黑客jQuery代码。当然有更好的方法来捕捉这些错误,而不是堵塞控制台日志。
I've found this question, but the solution involves hacking the jQuery code. Surely there's a better way to catch these errors and not clog up the console logs??
推荐答案
尝试这个:
$.ajax({
url: remoteURL,
type: 'GET',
error: function (err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
});
XHR听众:
$.ajax({
url: remoteURL,
type: 'GET',
xhr: function(){
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("error", function(evt){
alert("an error occured");
}, false);
xhr.addEventListener("abort", function(){
alert("cancelled");
}, false);
return xhr;
},
error: function (err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
});
这篇关于如何抓住jQuery AJAX错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!