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 for initiating an ajax request using jquery $. ajax () is as follows:
The Code 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 the 302 Found response, the running result in the browser is as follows:
The status code obtained in the callback functions of ajax complete () and error () is 404 instead of 302.
Why?
Found on stackoverflow
The Code is as follows:
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, the browser does not directly perform ajax callback processing, but first executes 302 redirection -- reads Location information from Response Headers, then, send a request to the Url in the Location. After receiving the response to the request, ajax callback is performed. The general process is as follows:
Jax> browser> server> 302> browser (redirect)> server> browser> ajax callback
In our test program, because the Redirection URL returned by 302 does not have a corresponding handler on the server, the 404 status code is obtained in the ajax callback function; if a corresponding URL exists, the resulting status code is 200.
Therefore, if you want to use location. href for redirection Based on the 302 response in an ajax request, it is not feasible.
How can this problem be solved?
Method 1
Continue to use ajax, modify the server code, and change the original 302 response to a json response, for example, the following sample code of ASP. net mvc:
The Code is as follows:
Return Json (new {status = 302, location = "/oauth/respond "});
Make a slight modification to the ajax code:
The Code is as follows:
$. Ajax ({
Url: '/oauth/respond ',
Type: 'post ',
Data: data,
DataType: 'json ',
Success: function (data ){
If (data. status = 302 ){
Location. href = data. location;
}
}
});
Method 2
Use form instead of ajax.
The Code is as follows:
<Form method = "post" action = "/oauth/respond">
</Form>
I have not studied this problem before, And I step on it several times. After this study, I think I will stay away from this trap in the future.