【问题标题】:jQuery ajax error functionjQuery ajax 错误函数
【发布时间】:2011-10-11 04:41:26
【问题描述】:

我有一个 ajax 调用将数据传递给一个页面,然后返回一个值。

我已从页面中检索到成功的调用,但我已对其进行了编码,以便它在 asp 中引发错误。如何从 jquery 中检索该错误?

例如:

cache: false,
url: "addInterview_Code.asp",
type: "POST",
datatype: "text",
data: strData,
success: function (html) {
    alert('successful : ' + html);
    $("#result").html("Successful");
},
error: function (error) {
    **alert('error; ' + eval(error));**
}

这是我不明白的错误位。在函数中我需要放置什么参数,以便我可以使用我在服务器中引发的错误消息。

【问题讨论】:

  • 这里有一个错字:它是dataType 而不是datatype。
  • 另外,jQuery says you can't use both success and error,就像你做的那样。
  • @alej27:措辞有点奇怪,但并不是说不能同时使用它们,而是说请求不会调用成功和错误(因为它们是互斥的) .
  • 在此处谨慎回答问题 从 jQuery 3.0 开始,.error 和 .success 上已弃用的内容已被删除,因此变得更加重要。

标签: jquery ajax


【解决方案1】:

Ajax error 函数中需要的参数是jqXHR, exception,你可以像下面这样使用它:

$.ajax({
    url: 'some_unknown_page.html',
    success: function (response) {
        $('#post').html(response.responseText);
    },
    error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    },
});

DEMO FIDDLE


参数

jqXHR:

它实际上是一个看起来像这样的错误对象

您也可以在自己的浏览器控制台中查看此内容,方法是在 error 函数中使用 console.log,例如:

error: function (jqXHR, exception) {
    console.log(jqXHR);
    // Your error handling logic here..
}

我们使用该对象的status 属性来获取错误代码,例如如果我们得到状态= 404,这意味着找不到请求的页面。它根本不存在。基于该状态代码,我们可以将用户重定向到登录页面或我们的业务逻辑需要的任何内容。

例外:

这是显示异常类型的字符串变量。因此,如果我们收到 404 错误,exception 文本将只是“错误”。同样,我们可能会收到“超时”、“中止”作为其他异常文本。


弃用通知: 自 jQuery 1.8 起,jqXHR.success()、jqXHR.error() 和 jqXHR.complete() 回调已弃用。准备 您最终删除的代码,请使用jqXHR.done()、jqXHR.fail()、 和jqXHR.always() 代替。

因此,如果您使用的是 jQuery 1.8 或更高版本,我们将需要更新成功和错误函数逻辑,例如:-

// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax("some_unknown_page.html")
    .done(function (response) {
        // success logic here
        $('#post').html(response.responseText);
    })
    .fail(function (jqXHR, exception) {
        // Our error logic here
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    })
    .always(function () {
        alert("complete");
    });

希望对你有帮助!

【讨论】:

  • 有趣的是不推荐使用 ajaxSetup。见api.jquery.com/jquery.ajaxsetup
  • @palaѕн 我认为您误读了弃用通知。如果您注意到,弃用通知是在谈论 jqXHR 方法的弃用,但是在您上面的示例中成功、错误和完成的使用是在 $.ajax 方法的对象内完成的。这尚未被弃用,您无需切换代码。但是,如果您更喜欢链接方法,那么您可以使用这种样式。当我读到“弃用......”时,这让我失望(无缘无故)。 :-)
  • 从 jQuery 3.0 开始,.error 和 .success 上的不推荐使用变得更加重要,因为它们已被删除
【解决方案2】:

试试这个:

error: function(jqXHR, textStatus, errorThrown) {
  console.log(textStatus, errorThrown);
}

如果您想通知前端有关验证错误,请尝试返回 json:

dataType: 'json',
success: function(data, textStatus, jqXHR) {
   console.log(data.error);
}

你的 asp 脚本应该返回:

{"error": true}

【讨论】:

  • textSttaus 和 errorThrown 是干什么用的?你能解释一下吗
【解决方案3】:

这是你如何拉出 asp 错误的方法。

              cache: false,
              url: "addInterview_Code.asp",
              type: "POST",
              datatype: "text",
              data: strData,
              success: function (html) {
                  alert('successful : ' + html);
                  $("#result").html("Successful");
              },
              error: function (jqXHR, textStatus, errorThrown) {
                  if (jqXHR.status == 500) {
                      alert('Internal error: ' + jqXHR.responseText);
                  } else {
                      alert('Unexpected error.');
                  }
              }

【讨论】:

    【解决方案4】:
    error(jqXHR, textStatus, errorThrown)
    

    http://api.jquery.com/jQuery.ajax/

    【讨论】:

    • 请提供一些解释,而不仅仅是一段代码和一个链接做文档。
    • 几乎一无所获。
    • 例如,您可以说“OP 正在使用函数错误(错误)但 jquery 正在调用函数错误(jqXHR、textStatus、errorThrown)。请注意 OP 的 sn- 中缺少的 2 个参数p."
    【解决方案5】:
              cache: false,
              url: "addInterview_Code.asp",
              type: "POST",
              datatype: "text",
              data: strData,
              success: function (html) {
                  alert('successful : ' + html);
                  $("#result").html("Successful");
              },
              error: function(data, errorThrown)
              {
                  alert('request failed :'+errorThrown);
              }
    

    【讨论】:

      【解决方案6】:

      你正在使用一个函数

      error(error) 
      

      但是jquery其实是在找一个带三个参数的函数:

      error(jqXHR, textStatus, errorThrown)
      

      您需要再添加两个参数。

      另外:请查看上面提到“已弃用”的所有 cmets :)

      $.ajax("www.stackoverflow.com/api/whatever", {
          dataType:"JSON"
          data: { id=1, name='example' }
      }).succes(function (result) {
          // use result
      }).error(function (jqXHR, textStatus, errorThrown) {
          // handle error
      });
      

      【讨论】:

      • 你需要再添加两个参数 - 这是大错特错。
      • 嗯。如果这就是你要说的——也许什么都不说?或者,您可以解释您的陈述并实际提供帮助。您的选择。
      • 在 JavaScript 中,假设您有一个方法 - function myMethod (err) { alert(err); },然后像 myMethod ("something is wrong", 500, some_object) 一样调用它 - 这将毫无问题地工作。根据您的声明,这仅在方法签名为function myMethod (err, status, some_object) 时才有效。忘记上面的例子,你在答案中的success事件的签名实际上是.success(data, status, xhr),但如果你只需要结果,我们通常像.success (data)一样绑定它,两者都可以。
      • 您通过添加此答案带来了什么附加值? IMO 您的答案中没有任何先前答案中缺少的信息。您所做的唯一一件事就是再次将这个问题拉到堆栈中。
      【解决方案7】:

      您可以这样使用:
      注意: responseText 返回服务器 response 和 statusText 返回预定义
      status error.for 的消息例如:
      responseText 在某些框架(例如 Yii2)中返回类似于 "Not Found (#404)" 但
      statusText 返回 "Not Found"。 p>

      $.ajax({
          cache: false,
          url: "addInterview_Code.asp",
          type: "POST",
          datatype: "text",
          data: strData,
          success: function (html) {
              alert('successful : ' + html);
              $("#result").html("Successful");
          },
          error: function (data) {
              console.log(data.status + ':' + data.statusText,data.responseText);
          }
      });
      

      【讨论】:

        【解决方案8】:

        来自 jquery.com:

        The jqXHR.success(), jqXHR.error(), and jqXHR.complete()
        callback methods introduced injQuery 1.5 are deprecated
        as of jQuery 1.8. To prepare your code for their eventual 
        removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
        

        如果您想要全局处理程序,您可以使用:

        .ajaxStart(), .ajaxStop(),
        .ajaxComplete(), .ajaxError(),
        .ajaxSuccess(), .ajaxSend()
        

        【讨论】:

          【解决方案9】:

          这对我有用。

          $.ajax({
              type: 'POST',
              url: url,
              data: {
                  menu: str
              },
              beforeSend: function(){
                  $.notify("sorting", "info");
              },
              success: function(data) {
                  $.notify("success", "success");
              },
              error: function (data) {
                  $.notify("Opps!", "error");
              }
              });
          

          【讨论】:

            猜你喜欢
            • 2011-01-12
            • 2011-01-07
            • 2013-10-27
            • 2012-01-08
            • 1970-01-01
            • 1970-01-01
            • 2013-01-13
            • 2019-01-01
            • 2012-07-22
            相关资源
            最近更新 更多