ajax與302響應代碼測試
更新時間:2013年10月23日 16:07:57 作者:
服務器端的響應是302 Found,在ajax的回調(diào)函數(shù)中能夠獲取這個狀態(tài)碼嗎?能夠從Response Headers中得到Location的值進行重定向嗎?讓我們來一起動手寫寫代碼看看實際情況吧。
在ajax請求中,如果服務器端的響應是302 Found,在ajax的回調(diào)函數(shù)中能夠獲取這個狀態(tài)碼嗎?能夠從Response Headers中得到Location的值進行重定向嗎?讓我們來一起看看實際情況。
使用jquery的$.ajax()發(fā)起ajax請求的javascript代碼如下:
$.ajax({
url: '/oauth/respond',
type: 'post',
data: data,
complete: function(jqXHR){
console.log(jqXHR.status);
},
error: function (xhr) {
console.log(xhr.status);
}
});
當服務器端返回302 Found的響應時,瀏覽器中的運行結(jié)果如下:
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.
原來,當服務器將302響應發(fā)給瀏覽器時,瀏覽器并不是直接進行ajax回調(diào)處理,而是先執(zhí)行302重定向——從Response Headers中讀取Location信息,然后向Location中的Url發(fā)出請求,在收到這個請求的響應后才會進行ajax回調(diào)處理。大致流程如下:
jax -> browser -> server -> 302 -> browser(redirect) -> server -> browser -> ajax callback
而在我們的測試程序中,由于302返回的重定向URL在服務器上沒有相應的處理程序,所以在ajax回調(diào)函數(shù)中得到的是404狀態(tài)碼;如果存在對應的URL,得到的狀態(tài)碼就是200。
所以,如果你想在ajax請求中根據(jù)302響應通過location.href進行重定向是不可行的。
return Json(new { status = 302, location = "/oauth/respond" });
ajax代碼稍作修改即可:
$.ajax({
url: '/oauth/respond',
type: 'post',
data: data,
dataType: 'json',
success: function (data) {
if (data.status == 302) {
location.href = data.location;
}
}
});
<form method="post" action="/oauth/respond">
</form>
以前沒研究透這個問題,踩了幾次坑。這次研究了一下,我想以后就會遠離這個坑了。
使用jquery的$.ajax()發(fā)起ajax請求的javascript代碼如下:
復制代碼 代碼如下:
$.ajax({
url: '/oauth/respond',
type: 'post',
data: data,
complete: function(jqXHR){
console.log(jqXHR.status);
},
error: function (xhr) {
console.log(xhr.status);
}
});
當服務器端返回302 Found的響應時,瀏覽器中的運行結(jié)果如下:
![]() |
在ajax的complete()與error()回調(diào)函數(shù)中得到的狀態(tài)碼都是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.
原來,當服務器將302響應發(fā)給瀏覽器時,瀏覽器并不是直接進行ajax回調(diào)處理,而是先執(zhí)行302重定向——從Response Headers中讀取Location信息,然后向Location中的Url發(fā)出請求,在收到這個請求的響應后才會進行ajax回調(diào)處理。大致流程如下:
jax -> browser -> server -> 302 -> browser(redirect) -> server -> browser -> ajax callback
而在我們的測試程序中,由于302返回的重定向URL在服務器上沒有相應的處理程序,所以在ajax回調(diào)函數(shù)中得到的是404狀態(tài)碼;如果存在對應的URL,得到的狀態(tài)碼就是200。
所以,如果你想在ajax請求中根據(jù)302響應通過location.href進行重定向是不可行的。
如何解決?
方法一
繼續(xù)用ajax,修改服務器端代碼,將原來的302響應改為json響應,比如下面的ASP.NET MVC示例代碼:
復制代碼 代碼如下:
return Json(new { status = 302, location = "/oauth/respond" });
ajax代碼稍作修改即可:
復制代碼 代碼如下:
$.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>
以前沒研究透這個問題,踩了幾次坑。這次研究了一下,我想以后就會遠離這個坑了。
相關(guān)文章
微信小程序 image組件binderror使用例子與js中的onerror區(qū)別
這篇文章主要介紹了微信小程序 image組件binderror使用例子與js中的onerror區(qū)別的相關(guān)資料,需要的朋友可以參考下2017-02-02