How to pass something to Ajax.Complete jquery
I have this problem that my sites uses alot of ajax and when a user times out they still are on my page. Now say a user walks away for 10mins(the timeout is set 10mins) now the user is timed out but still on the page.
开发者_开发百科So they could do a "save" request but now all my action methods that the ajax requests go to have an asp.net mvc authorize tag ontop of it. If a user fails this authentication then they should be redirected to the "signin page" but since it is ajax request they won't get send to the "signin page" nothing will happen.
So I was thinking maybe I could somehow pass something back(maybe if they are still authenticated) back to ajax.Complete and if it is "false" then do a redirect from javascript.
However I don't know how to do this. I don't know how to pass something back to it, how to write my controller method.
If MVC produces a 401 Unathorized response then the failure callback for the jQuery ajax call should get invoked and provide you with the XmlHttpRequest object. You can inspect the XmlHttpRequest for as status code of 401 XmlHttpRequest.status == 401
and then change the page location via your script to the login, even provide a message if you like. Regardless if it produces a 401, any non-success status code should invoke the failure callback of the ajax request and you should be able to handle your situation in the method set to handle failures.
Something like the below generalized code could handle your failures.
function(xhr, errorText, ex){
if(xhr.status == 401) {
//.. alert user and redirect to login ..
document.location = 'myloginpage.html';
}
...
}
An easy way might be to just have the page redirect after the timeout occurs to a logout/login page. Most sites that have timeouts like that will give you a warning first. If you click "OK" your timeout is reset. If you click "Cancel" or just leave it, the page will timeout, you will be logged out and you will be redirected to another page.
精彩评论