在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); } });
當服務器端返回302 Found的響應時,瀏覽器中的運行結果如下:
在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.
原來,當服務器將302響應發給瀏覽器時,瀏覽器並不是直接進行ajax回調處理,而是先執行302重定向——從Response Headers中讀取Location信息,然后向Location中的Url發出請求,在收到這個請求的響應后才會進行ajax回調處理。大致流程如下:
ajax -> browser -> server -> 302 -> browser(redirect) -> server -> browser -> ajax callback
而在我們的測試程序中,由於302返回的重定向URL在服務器上沒有相應的處理程序,所以在ajax回調函數中得到的是404狀態碼;如果存在對應的URL,得到的狀態碼就是200。
所以,如果你想在ajax請求中根據302響應通過location.href進行重定向是不可行的。
如何解決?
【方法一】
繼續用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>
以前沒研究透這個問題,踩了幾次坑。這次研究了一下,並寫出博客,我想以后就會遠離這個坑了。