jQuery 如何捕获 Ajax 查询发布错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2833951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I catch an Ajax query post error?
提问by TTCG
I would like to catch the error and show the appropriate message if the Ajax request fails.
如果 Ajax 请求失败,我想捕获错误并显示适当的消息。
My code is like the following, but I could not manage to catch the failing Ajax request.
我的代码如下所示,但我无法捕获失败的 Ajax 请求。
function getAjaxData(id)
{
$.post("status.ajax.php", {deviceId : id}, function(data){
var tab1;
if (data.length>0) {
tab1 = data;
}
else {
tab1 = "Error in Ajax";
}
return tab1;
});
}
I found out that, "Error in Ajax" is never executed when the Ajax request failed.
我发现,当 Ajax 请求失败时,永远不会执行“Ajax 中的错误”。
How do I handle the Ajax error and show the appropriate message if it fails?
我如何处理 Ajax 错误并在失败时显示适当的消息?
回答by choise
Since jQuery 1.5 you can use the deferred objects mechanism:
从 jQuery 1.5 开始,您可以使用延迟对象机制:
$.post('some.php', {name: 'John'})
.done(function(msg){ })
.fail(function(xhr, status, error) {
// error handling
});
Another way is using .ajax
:
另一种方法是使用.ajax
:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
回答by Michael Venable
jQuery 1.5 added deferred objects that handle this nicely. Simply call $.post
and attach any handlers you'd like after the call. Deferred objects even allow you to attach multiple success and error handlers.
jQuery 1.5 添加了可以很好地处理这个问题的延迟对象。只需在通话后调用$.post
并附加您想要的任何处理程序。延迟对象甚至允许您附加多个成功和错误处理程序。
Example:
例子:
$.post('status.ajax.php', {deviceId: id})
.done( function(msg) { ... } )
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
});
Prior to jQuery 1.8, the function done
was called success
and fail
was called error
.
在此之前的jQuery 1.8,该函数done
被调用success
和fail
被调用error
。
回答by jAndy
$.ajax({
type: 'POST',
url: 'status.ajax.php',
data: {
deviceId: id
},
success: function(data){
// your code from above
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
回答by marknery
$.post('someUri', { },
function(data){ doSomeStuff })
.fail(function(error) { alert(error.responseJSON) });
回答by karim79
A simple way is to implement ajaxError:
一个简单的方法是实现ajaxError:
Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the .ajaxError() method are executed at this time.
每当 Ajax 请求完成并出现错误时,jQuery 就会触发 ajaxError 事件。任何和所有已使用 .ajaxError() 方法注册的处理程序都将在此时执行。
For example:
例如:
$('.log').ajaxError(function() {
$(this).text('Triggered ajaxError handler.');
});
I would suggest reading the ajaxErrordocumentation. It does more than the simple use-case demonstrated above - mainly its callback accepts a number of parameters:
我建议阅读ajaxError文档。它不仅仅是上面演示的简单用例 - 主要是它的回调接受许多参数:
$('.log').ajaxError(function(e, xhr, settings, exception) {
if (settings.url == 'ajax/missing.html') {
$(this).text('Triggered ajaxError handler.');
}
});
回答by manolo
You have to log the responseText:
您必须记录 responseText:
$.ajax({
type: 'POST',
url: 'status.ajax.php',
data: {
deviceId: id
}
})
.done(
function (data) {
//your code
}
)
.fail(function (data) {
console.log( "Ajax failed: " + data['responseText'] );
})
回答by Mark Giblin
you attach the .onerror handler to the ajax object, why people insist on posting JQuery for responses when vanila works cross platform...
您将 .onerror 处理程序附加到 ajax 对象,为什么人们坚持在 vanila 跨平台工作时发布 JQuery 以进行响应......
quickie example:
快速示例:
ajax = new XMLHttpRequest();
ajax.open( "POST", "/url/to/handler.php", true );
ajax.onerror = function(){
alert("Oops! Something went wrong...");
}
ajax.send(someWebFormToken );