In an ajax request, if the server-side response is 302 Found, can this status code be obtained in the ajax callback function? Can I get the Location value from Response Headers for redirection? Let's take a look at the actual situation.
The javascript code to initiate an ajax request using jquery's $.ajax() is as follows:
$.ajax({
url: '/oauth/respond',
type: 'post',
data: data,
complete: function(jqXHR){
console.log(jqXHR.status);
},
error: function (xhr) {
console.log(xhr.status);
}
});
When the server returns a 302 Found response, the running results in the browser are as follows:
The status codes obtained in the complete() and error() callback functions of ajax are both 404, not 302.
Why is this?
Found on 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.
It turns out that when the server sends a 302 response to the browser When using the browser, the browser does not directly perform ajax callback processing, but first performs a 302 redirect—reading the Location information from the Response Headers, and then making a request to the Url in the Location. After receiving the response to this request, Perform ajax callback processing. The general process is as follows:
jax -> browser -> server -> 302 -> browser(redirect) -> server -> browser -> ajax callback
And in our test program , since the redirect URL returned by 302 does not have a corresponding handler on the server, the 404 status code obtained in the ajax callback function is 200. If the corresponding URL exists, the status code obtained is 200.
So, if you want to redirect via location.href based on 302 response in ajax request it is not feasible.
How to solve it?
Method 1
Continue to use ajax, modify the server-side code, and change the original 302 response to a json response, such as the following ASP.NET MVC sample code:
return Json(new { status = 302, location = "/oauth/respond" }) ;
The ajax code can be modified slightly:
$.ajax({
url: '/oauth/respond',
type: 'post',
data: data,
dataType: 'json',
Success: function (data) {
🎜>
Method 2
Instead of ajax, use form instead.
Copy code
I didn’t study this issue thoroughly before, and I stepped on several pitfalls. After researching this time, I think I will stay away from this trap in the future.