如何根据我的情况下,服务器响应触发jquery.ajax()错误回调? [英] how to trigger jquery.ajax() error callback based on server response in my case?

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

问题描述

使用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

 }

});

我有两个问题要问基于上述code:

I got two questions to ask based on above code:

  1. 在将在jquery.ajax()错误的回调被称为??

如果服务器响应我用绳子消息JSON对象的中存在错误的。这意味着请求仍然发送成功,但我得到的服务器响应 {消息:有错误}

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对象如 {一条消息:是一个错误} ,服务器可以做一些事情因此,这种反应可以在 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五百分之四百零四或任何其他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()错误回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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