如何从AJAX调用错误的处理? [英] How do you handle errors from AJAX calls?

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

问题描述

让我们说我有以下jQuery的AJAX调用:

Let's say I have the following jQuery AJAX call:

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
        // Do stuff
   }
 });

现在,当这个AJAX调用是我想要的服务器端code通过一些错误运行处理检查(例如为用户仍然登录,他们有权限使用这个电话,是数据有效等)。如果检测到错误,我怎么泡的错误消息返回到客户端?

Now, when this AJAX call is made I want the server-side code to run through a few error handling checks (e.g. is the user still logged in, do they have permission to use this call, is the data valid, etc). If an error is detected, how do I bubble that error message back up to the client side?

我最初的想法是将返回一个JSON对象有两个字段:错误和的errorMessage。这些字段将随后在jQuery的AJAX调用进行检查:

My initial thought would be to return a JSON object with two fields: error and errorMessage. These fields would then be checked in the jQuery AJAX call:

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
       if (result.error == "true") 
       {
           alert("An error occurred: " & result.errorMessage);
       }
       else 
       {
           // Do stuff
       }
   }
 });

这感觉有点笨重给我,但它的作品。有没有更好的选择?

This feels a bit clunky to me, but it works. Is there a better alternative?

推荐答案

就个人而言,我也有类似的code以下code在我的图书馆。

Personally, I have similar code to the following code in my library.

$.ajaxSetup({
    error: function(xhr){
        alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
    }
});

jQuery的文档的Ajax / jQuery.ajaxSetup

要泡的最佳方式从服务器端(使用PHP)到客户端的错误是通过Ajax请求某处发送一个报头400的(它总是与错误有关)。一旦Ajax请求接收到这一点,就会引发你的错误的功能。这也意味着,你不必定义一个错误:在每一个$就电话叫

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function. This also means that you do not have to define an error: call in every $.ajax call.

header('HTTP/1.0 419 Custom Error');

w3.org头信息报价

错误4XX,5XX 在4XX codeS旨在用于在客户端似乎出现了偏差的情况下,与5XX codeS的案件中,服务器知道服务器已经犯了错误。这是不可能的,一般区分这些情况下,这样的区别是仅供参考。 主体部分可以包含描述人类可读的格式错误的文件。该文件是MIME格式,并且只能在文本/纯,文本/ HTML或一个用于在请求中指定为可以接受的格式。

Error 4xx, 5xx The 4xx codes are intended for cases in which the client seems to have erred, and the 5xx codes for the cases in which the server is aware that the server has erred. It is impossible to distinguish these cases in general, so the difference is only informational. The body section may contain a document describing the error in human readable form. The document is in MIME format, and may only be in text/plain, text/html or one for the formats specified as acceptable in the request.

这篇关于如何从AJAX调用错误的处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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