如何捕获Ajax查询post错误?

如果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错误并在出现错误时显示相应的消息?

由于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"); } }); 

jQuery 1.5添加了可以很好地处理这个事件的延迟对象。 只需致电$.post然后附上您想要的任何处理程序。 延迟对象甚至允许您附加多个成功和error handling程序。

例:

 $.post('status.ajax.php', {deviceId: id}) .done( function(msg) { ... } ) .fail( function(xhr, textStatus, errorThrown) { alert(xhr.responseText); }); 

在jQuery 1.8之前, done的function被称为successfail被称为error

 $.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); } }); 
 $.post('someUri', { }, function(data){ doSomeStuff }) .fail(function(error) { alert(error.responseJSON) }); 

一个简单的方法是实现ajaxError :

每当Ajax请求发生错误时,jQuery就会触发ajaxError事件。 任何和所有已经用.ajaxError()方法注册的处理程序都是在这个时候执行的。

例如:

 $('.log').ajaxError(function() { $(this).text('Triggered ajaxError handler.'); }); 

我会build议阅读ajaxError文档。 它不仅仅是上面演示的简单用例 – 主要是它的callback接受了许多参数:

 $('.log').ajaxError(function(e, xhr, settings, exception) { if (settings.url == 'ajax/missing.html') { $(this).text('Triggered ajaxError handler.'); } }); 

我通过在我的jQuery ajax调用中声明datatype: 'json'来解决这个问题。