如何從jQuery.ajax獲取響應狀態代碼?在下面的代碼中,我要做的就是從jQuery.ajax調用中獲取HTTP響應代碼。然后,如果代碼為301(永久移動),則顯示“位置”響應標頭:<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>
<title>jQuery 301 Trial</title>
<script src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
function get_resp_status(url) {
$.ajax({
url: url,
complete: function (jqxhr, txt_status) {
console.log ("Complete: [ " + txt_status + " ] " + jqxhr);
// if (response code is 301) {
console.log ("Location: " + jqxhr.getResponseHeader("Location"));
// }
}
});
}
</script>
<script type="text/javascript">
$(document).ready(function(){
$('a').mouseenter(
function () {
get_resp_status(this.href);
},
function () {
}
);
});
</script></head><body>
<a href="http://ow.ly/4etPl">Test 301 redirect</a>
<a href="http://cnn.com/not_found">Test 404 not found</a></body></html>有人能指出我哪里錯了嗎?當我檢查Firebug中的'jqxhr'對象時,我找不到狀態代碼,也找不到'Location'響應頭。我在'完成'的最后一行設置了斷點。非常感謝。
3 回答

慕后森
TA貢獻1802條經驗 獲得超5個贊
當您的XHR請求返回重定向響應(HTTP狀態301,302,303,307)時,將XMLHttpRequest
自動跟隨重定向的URL并返回該URL的狀態代碼。
您可以通過status
xhr對象的屬性獲取非重定向狀態代碼(200,400,500 等)。
所以你不能從響應頭重定向的位置301
,302
,303
或307
請求。
您可能必須更改服務器邏輯,以便能夠處理重定向,而不是讓瀏覽器執行此操作。一個示例實現。
- 3 回答
- 0 關注
- 1769 瀏覽
相關問題推薦
添加回答
舉報
0/150
提交
取消