我怎样才能赶上jQuery的AJAX错误? [英] How can I catch jQuery AJAX errors?
问题描述
当一个AJAX请求被提交到一个站点,服务器端错误很容易与jQuery的承诺的方式进行处理。 .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:
XMLHtt prequest无法加载的http:// someotherserver / API / blahblah
。起源
的http://本地主机:52625
不会被允许访问控制 - 允许 - 原产地
XMLHttpRequest cannot load
http://someotherserver/api/blahblah
. Originhttp://localhost:52625
is not allowed by Access-Control-Allow-Origin.
是的,我知道CORS ...这不是问题。什么我实际上做是试图一个Web 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的请求语法选项:
I'm aware of the error
option in the jQuery request syntax:
$.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的code。肯定有更好的方法来捕获这些错误,而不是堵塞的控制台日志??
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监听器:
XHR Listener:
$.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屋!