如何在jquery ajax中处理204响应? [英] How to handle a 204 response in jquery ajax?

查看:1243
本文介绍了如何在jquery ajax中处理204响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我已声明成功和错误的ajax选项(响应为204)一样,ajax方法进入选项成功,这会导致错误.

As I have declared success and error ajax options, where the response is 204, the ajax method goes to option success which leads to an error.

根据我们可以使用的文档,StatusCode或Complete方法,但是这里的缺点是必须声明所有状态代码,例如2?系列3?系列,4 ??系列!由于这些响应是动态的,因此我不确定http状态代码.

As per the documentation we can use, StatusCode or Complete methods but the disadvantage here is have to declare all the status code like 2?? series, 3?? series, 4?? series! As these response are dynamic and I am not sure about the http status code.

那么,哪种方法在jquery ajax中处理http状态代码更好呢?

So, which is better way to handle http status code in jquery ajax?

推荐答案

从jQuery 1.5开始,由$ .ajax()返回的jqXHR对象实现了Promise接口. done函数中的第三个参数是jqXHR对象.该对象具有结果的http状态代码的属性.

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface. The third argument in the done function is a jqXHR object. This object has a property for the http status code of the result.

jqXHR.done(function(data(text,textStatus,jqXHR){});替代 构造为成功回调选项,.done()方法将替换 不推荐使用的jqXHR.success()方法.请参阅deferred.done()以获取 实施细节. 链接

jqXHR.done(function(data, textStatus, jqXHR) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details. link

    $.ajax({
      url: "http://fiddle.jshell.net/favicon.png",
      beforeSend: function ( xhr ) {
          xhr.overrideMimeType("text/plain; charset=x-user-defined"); 
      }
    }).done(function ( data, textStatus, jqXHR) {
       console.log(jqXHR.status); //handle your 204 or other status codes here
    });

小提琴 http://jsfiddle.net/puleos/fVa7X/

假设您要将所有非200状态代码都视为错误,则可以执行以下操作:

Assuming you want to treat all non 200 status codes as an error you could do something like this:

var p = $.ajax({
          url: "http://fiddle.jshell.net/favicon.png",
          beforeSend: function ( xhr ) {
             xhr.overrideMimeType("text/plain; charset=x-user-defined"); 
          }
        });

p.done(function(data, textStatus, jqXHR) {
  if(jqXHR.status !== 200) {
     handleError(jqXHR.status);
     return;
  }
  // Normal processing here
});

p.fail(function(jqXHR, textStatus) {
   handleError(jqXHR.status); 
});

这篇关于如何在jquery ajax中处理204响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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