如何根据服务器响应触发jquery.ajax()错误回调,而不是HTTP 500? [英] How to trigger jquery.ajax() error callback based on server response, not HTTP 500?

查看:232
本文介绍了如何根据服务器响应触发jquery.ajax()错误回调,而不是HTTP 500?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过使用jquery ajax函数,我可以执行以下操作:

By using jquery ajax function, I can do something like:

$.ajax({

  url: url,
  type: 'GET',
  async: true,
  dataType: 'json',
  data: data,

 success: function(data) {

     //Handle server response here

  },

 error: function(xhr, status, error){

    //Handle failure here

 }

});

根据以上代码,我有两个问题要问:

I got two questions to ask based on above code:


  1. 何时调用jquery.ajax()错误回调??

如果服务器使用字符串消息出现错误向我回复了json对象,该怎么办?这意味着请求仍然成功发送,但我得到服务器响应 {message:有一个错误}

What if server response to me a json object with string message "There is an error". Which means the request is still send successfully, but I got server response {message: "There is an error"}.

我认为无论服务器响应什么字符串值,如果客户端得到服务器的响应, jquery。 ajax() 成功无论如何都会触发回调。

I think no matter what string value server is responsed, if client got server's response, the jquery.ajax() success callback will be triggered anyway.

我想询问是否服务器特别是给我一个JSON对象,其字符串值类似于 {message:'有一个错误'} ,服务器可以执行某些操作,以便可以在中处理此响应jquery.ajax() 错误回调而不是成功回调?

I'd like to ask if server specifically returns to me a JSON object with string value like {message: 'There is an error'}, could server do something so that this response could be handled in jquery.ajax() error callback instead of success callback?

推荐答案

当服务器的响应不符合您的预期时,将执行错误回调。因此,例如在这种情况下:

The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:


  • HTTP 404/500或收到任何其他HTTP错误消息

  • 收到了不正确类型的数据(即您已经预期JSON,您已收到其他内容)。

在您的情况下数据是正确的(这是一个JSON消息)。如果要根据接收数据的值手动触发错误回调,则可以非常简单地完成。只需将错误的匿名回调更改为命名函数。

In your situation the data is correct (it's a JSON message). If you want to manually trigger the error callback based on the value of the received data you can do so quite simple. Just change the anonymous callback for error to named function.

function handleError(xhr, status, error){

    //Handle failure here

 }

$.ajax({

  url: url,
  type: 'GET',
  async: true,
  dataType: 'json',
  data: data,

 success: function(data) {
     if (whatever) {
         handleError(xhr, status, ''); // manually trigger callback
     }
     //Handle server response here

  },

 error: handleError
});

这篇关于如何根据服务器响应触发jquery.ajax()错误回调,而不是HTTP 500?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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