如果Ajax请求失败,我想捕获错误并显示相应的消息。
我的代码如下所示,但我无法捕获失败的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;
});
}
我发现,当Ajax请求失败时,“Ajax中的错误”永远不会被执行。
如何处理Ajax错误并在失败时显示相应的消息?
答案 0 :(得分:274)
jQuery 1.5添加了延迟对象,可以很好地处理这个问题。只需致电$.post
并附上您在通话后想要的任何处理程序。延迟对象甚至允许您附加多个成功和错误处理程序。
示例:
$.post('status.ajax.php', {deviceId: id})
.done( function(msg) { ... } )
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
});
在jQuery 1.8之前,函数done
被称为success
而fail
被称为error
。
答案 1 :(得分:266)
从jQuery 1.5开始,您可以使用延迟对象机制:
$.post('some.php', {name: 'John'})
.done(function(msg){ })
.fail(function(xhr, status, error) {
// error handling
});
另一种方法是使用.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");
}
});
答案 2 :(得分:88)
$.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);
}
});
答案 3 :(得分:14)
$.post('someUri', { },
function(data){ doSomeStuff })
.fail(function(error) { alert(error.responseJSON) });
答案 4 :(得分:13)
一种简单的方法是实施ajaxError:
每当Ajax请求完成时 如果出现错误,jQuery会触发 ajaxError事件。任何和所有处理程序 已经注册的 .ajaxError()方法执行于 这一次。
例如:
$('.log').ajaxError(function() {
$(this).text('Triggered ajaxError handler.');
});
我建议您阅读ajaxError文档。它不仅仅是上面演示的简单用例 - 主要是它的回调接受了许多参数:
$('.log').ajaxError(function(e, xhr, settings, exception) {
if (settings.url == 'ajax/missing.html') {
$(this).text('Triggered ajaxError handler.');
}
});
答案 5 :(得分:0)
您必须记录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'] );
})
答案 6 :(得分:0)
您将.onerror处理程序附加到ajax对象,为什么当vanila跨平台工作时人们坚持要发布JQuery以获得响应...
快速示例:
ajax = new XMLHttpRequest();
ajax.open( "POST", "/url/to/handler.php", true );
ajax.onerror = function(){
alert("Oops! Something went wrong...");
}
ajax.send(someWebFormToken );
答案 7 :(得分:0)
如果您想使用.then()which has a subtle difference in comparison with .done():
return $.post(url, payload)
.then(
function (result, textStatus, jqXHR) {
return result;
},
function (jqXHR, textStatus, errorThrown) {
return console.error(errorThrown);
});