简体   繁体   English

使用statusCode处理jQuery AJAX失败

[英]Handling jQuery AJAX failures with statusCode

I'm trying to globally detect and react to a certain statusCode, using jQuery's statusCode function. 我正在尝试使用jQuery的statusCode函数来全局检测并响应特定的statusCode。 However, when a specific call fails, it seems be hitting both the original error and THEN the statusCode. 但是,当一个特定的调用失败时,它似乎同时碰到了原始错误,然后又碰到了statusCode。 Why is this happening? 为什么会这样呢? Can it just hit the statusCode first? 可以先打一下statusCode吗?

Here is my ajaxSetup: 这是我的ajaxSetup:

$.ajaxSetup({
    statusCode: {
            412 : function(data) {
               alert('do something!');
            }
     }
});

And here is a sample instance: 这是一个示例实例:

$.ajax({
     type: "GET", 
     url: 'a_url.json', 
     dataType: 'json',
     data : {
          'id': dnaRefTOID
     },
     success: function(data) {
          alert('success');
     },
     error : function(xhr, status, error) {
           alert(xhr.statusText);
     }
 });

What I'm seeing is that the call is hitting 'error' before hitting statusCode. 我看到的是,在达到statusCode之前,该呼叫已达到“错误”。 I want it to hit statusCode and statusCode always. 我希望它总是打statusCode和statusCode。 This example is obviously spread across many ajax calls, so I don't want to use an if statement in each error or else it defeats the point of using statusCode. 这个示例显然分散在许多ajax调用中,所以我不想在每个错误中使用if语句,否则它会破坏使用statusCode的目的。

Does anyone have any ideas? 有人有什么想法吗?

As far as I know you can't achieve that without changing jQuery itself. 据我所知,不更改jQuery本身是无法实现的。 You could do something like this: 您可以执行以下操作:

$(document).ajaxError(function(event, jqxhr, settings, exception) {
   if (jqxhr.status == 412) {
      //handle status code 412 here
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM