如何捕获Ajax查询发布错误?

TTC*_*TCG 200 ajax error-handling jquery 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;
    });
}
Run Code Online (Sandbox Code Playgroud)

我发现,当Ajax请求失败时,永远不会执行"Ajax中的错误".

如果失败,我如何处理Ajax错误并显示相应的消息?

cho*_*ise 286

从jQuery 1.5开始,您可以使用延迟对象机制:

$.post('some.php', {name: 'John'})
    .done(function(msg){  })
    .fail(function(xhr, status, error) {
        // error handling
    });
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用.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");
  }
});
Run Code Online (Sandbox Code Playgroud)

  • @Yuck $ .post可以使用延迟对象接受错误回调.请看下面的答案,作为一个例子. (14认同)
  • 从jQuery 1.8开始,上面的成功和错误回调已经过时了http://api.jquery.com/jQuery.post/ (3认同)
  • 另外,我想让`$ .ajax`更具可读性是为你的`data`使用哈希.例如:`{name:'John',location:'Boston'}` (2认同)

Mic*_*ble 281

jQuery 1.5添加了延迟对象,可以很好地处理这个问题.$.post在通话结束后,只需致电并附上您想要的任何处理程序.延迟对象甚至允许您附加多个成功和错误处理程序.

例:

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

在此之前的jQuery 1.8,该函数done被调用successfail被调用error.

  • 这应该是公认的答案.目前接受的答案是"使用不同的方法"; 这个答案说"这里是如何使你的方法工作".后者通常在SO上是优选的.实际上,这应该包含在$ .post文档中! (22认同)
  • +1非常好,但仍然没有疯狂的语法.希望它在未来的版本中得到统一. (3认同)
  • `xhr.responseText` 似乎是失败回调大海捞针。但我建议将 `dataType: 'text'` 添加到 $.post 的第二个参数。这[可能](https://api.jquery.com/jQuery.Ajax/#data-types)有助于引导不同内容类型的错误消息显示在responseText中。但我没查过。 (3认同)
  • http://api.jquery.com/deferred.fail,http://api.jquery.com/deferred.done用于文档 (2认同)
  • 顺便说一句,还有 `responseJSON` 属性,在 ajax 类型为 `json` 的情况下也非常方便。 (2认同)

jAn*_*ndy 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);
  }
});
Run Code Online (Sandbox Code Playgroud)


mar*_*ery 14

$.post('someUri', { }, 
  function(data){ doSomeStuff })
 .fail(function(error) { alert(error.responseJSON) });
Run Code Online (Sandbox Code Playgroud)

  • 在这里添加更多解释将有助于未来的读者. (4认同)

kar*_*m79 13

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

每当Ajax请求因错误而完成时,jQuery都会触发ajaxError事件.已经使用.ajaxError()方法注册的任何和所有处理程序都会在此时执行.

例如:

$('.log').ajaxError(function() {
  $(this).text('Triggered ajaxError handler.');
});
Run Code Online (Sandbox Code Playgroud)

我建议阅读ajaxError文档.它不仅仅是上面演示的简单用例 - 主要是它的回调接受了许多参数:

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