jQuery post 失败回调不显示代码 400 的响应

jQuery post fail callback does not display response for code 400

我有以下 jQuery post 请求:

$.post("ajax.php", data).done(
    function(response){
        // do something when response is ok
     }
   ).fail(
    function(response){
          $("#error").html(response);
     }
 );

在我的 ajax.php 文件中,当出现问题时,我 return HTTP 响应代码 400 带有一条消息:

header("HTTP/1.0 400 Error");
echo "Some error message";
exit();

当我在浏览器中检查错误调用的响应时,我可以看到状态代码 Status Code:400 Bad Request 和我在错误消息中传递的响应文本。但是 jQuery 的 .fail 回调没有显示我的 response

如何获得对 fail/error 响应文本的访问权限?

编辑

我测试了我的代码,.fail 回调被触发,我只是无法获得显示的响应消息。

您需要使用jqXHR:

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

.fail 是 jqXHR 对象的可用 Promise 方法之一,

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

您可以使用 responseText 属性 来获取错误消息:

$.post("ajax.php", data).done(
    function(response){
        // do something when response is ok
     }
   ).fail(
    function(jqXHR, textStatus, errorThrown) {
          $("#error").html(jqXHR.responseText);
     }
 );

参考:http://api.jquery.com/jquery.ajax/#jqXHR

我总是使用 500 作为 ajax 失败代码,它通常会被 .fail 为我提取。 JQ API for .post 有一长串嵌套链接,描述了它们如何处理 JqXHR 对象以及它如何与 JQ 作为一个整体进行交互。

由于您的状态没有触发 .fail,您可以像这样在 .success 或 .done 函数中检查您的特定状态代码是否成功。

//post stuff
.success(function(response){  
   if(response.status == 400){
      //error stuff
   }
});

在 .done 或 .success 中执行您自己的检查的优点是您可以为您希望从服务器 return 的不同状态定义一些漂亮的行为。有许多不同的方法来处理 ajax return 和定义回调行为。

**这是另一个有其他解决方案的 SO 问题。

**这里的语法略有不同,因为这个问题的重点是.ajax方法而不是.post,但提出的想法和解决方案应该仍然有效。