ajax+get+status,ajax - How do I get the HTTP status code with jQuery? - Stack Overflow

在使用jQuery v3进行AJAX请求时遇到问题,当从JSON API获取数据时,只有在状态码为成功时jQuery才会解析JSON。此外,回调参数的顺序会根据状态码变化。解决方法是利用.always()链式方法进行数据清理。以下是示例代码:$.ajax({...}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I have had major issues with ajax + jQuery v3 getting both the response status code and data from JSON APIs. jQuery.ajax only decodes JSON data if the status is a successful one, and it also swaps around the ordering of the callback parameters depending on the status code. Ugghhh.

The best way to combat this is to call the .always chain method and do a bit of cleaning up. Here is my code.

$.ajax({

...

}).always(function(data, textStatus, xhr) {

var responseCode = null;

if (textStatus === "error") {

// data variable is actually xhr

responseCode = data.status;

if (data.responseText) {

try {

data = JSON.parse(data.responseText);

} catch (e) {

// Ignore

}

}

} else {

responseCode = xhr.status;

}

console.log("Response code", responseCode);

console.log("JSON Data", data);

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值