在ajax請(qǐng)求中,如果服務(wù)器端的響應(yīng)是302 Found,在ajax的回調(diào)函數(shù)中能夠獲取這個(gè)狀態(tài)碼嗎?能夠從Response Headers中得到Location的值進(jìn)行重定向嗎?讓我們來(lái)一起看看實(shí)際情況。
使用jquery的$.ajax()發(fā)起ajax請(qǐng)求的javascript代碼如下:
復(fù)制代碼 代碼如下:
$.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()回調(diào)函數(shù)中得到的狀態(tài)碼都是404,而不是302。
這是為什么呢?
在stackoverflow上找到了
復(fù)制代碼 代碼如下:
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.
如何解決?
方法一
繼續(xù)用ajax,修改服務(wù)器端代碼,將原來(lái)的302響應(yīng)改為json響應(yīng),比如下面的ASP.NET MVC示例代碼:
復(fù)制代碼 代碼如下:
return Json(new { status = 302, location = "/oauth/respond" });
復(fù)制代碼 代碼如下:
$.ajax({
url: '/oauth/respond',
type: 'post',
data: data,
dataType: 'json',
success: function (data) {
if (data.status == 302) {
location.href = data.location;
}
}
});
方法二
不用ajax,改用form。
復(fù)制代碼 代碼如下:
<form method="post" action="/oauth/respond">
</form>
新聞熱點(diǎn)
疑難解答
圖片精選