gpt4 book ai didi

jquery - 如何在 jquery ajax 中处理 204 响应?

转载 作者:行者123 更新时间:2023-12-03 21:51:26 24 4
gpt4 key购买 nike

由于我已经声明了 success 和 error ajax 选项,其中响应为 204,ajax 方法会转到选项 success,从而导致错误。

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

那么,在 jquery ajax 中处理 http 状态代码的更好方法是什么?

最佳答案

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

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
});

fiddle http://jsfiddle.net/puleos/fVa7X/

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

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 - 如何在 jquery ajax 中处理 204 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16219595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com