在ajax請求中,如果服務器端的響應是302 Found,在ajax的回調函數中能夠獲取這個狀態碼嗎?能夠從Response Headers中得到Location的值進行重定向嗎?讓我們來一起看看實際情況。
使用jquery的$.ajax()發起ajax請求的javascript代碼如下:
復制代碼 代碼如下:
$.ajax({
url: '/oauth/respond',
type: 'post',
data: data,
complete: function(jqXHR){
console.log(jqXHR.status);
},
error: function (xhr) {
console.log(xhr.status);
}
});
在ajax的complete()與error()回調函數中得到的狀態碼都是404,而不是302。
這是為什么呢?
在stackoverflow上找到了
復制代碼 代碼如下:
You can't handle redirects with XHR callbacks because the browser takes care of them automatically. You will only get back what at the redirected location.
如何解決?
方法一
繼續用ajax,修改服務器端代碼,將原來的302響應改為json響應,比如下面的ASP.NET MVC示例代碼:
復制代碼 代碼如下:
return Json(new { status = 302, location = "/oauth/respond" });
復制代碼 代碼如下:
$.ajax({
url: '/oauth/respond',
type: 'post',
data: data,
dataType: 'json',
success: function (data) {
if (data.status == 302) {
location.href = data.location;
}
}
});
方法二
不用ajax,改用form。
復制代碼 代碼如下:
<form method="post" action="/oauth/respond">
</form>
新聞熱點
疑難解答
圖片精選