如何捕获 Ajax 查询发布错误? [英] How do I catch an Ajax query post error?

查看:25
本文介绍了如何捕获 Ajax 查询发布错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 Ajax 请求失败,我想捕获错误并显示相应的消息.

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.

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 中的错误".

I found out that, "Error in Ajax" is never executed when the Ajax request failed.

如何处理 Ajax 错误并在失败时显示相应的消息?

How do I handle the Ajax error and show the appropriate message if it fails?

推荐答案

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

Since jQuery 1.5 you can use the deferred objects mechanism:

$.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");
  }
});

这篇关于如何捕获 Ajax 查询发布错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆