I have an ajax heavy web-application built using PHP, jQuery.
I am looking for solution to below issues.
(1). User 开发者_C百科is running the application in browser. Internet goes off. The browser makes an ajax request to the server and the request obviously fails due to absence of network. I want a cross-browser way (including Windows/MAC/Linux) to detect this failure and show a notification to the user.
(2). Network is On. The browser makes an ajax request to server and before it receives the response the network goes off. So when the server sends the response the client is offline. Here also I want to show a notification to the user regarding the error. Gmail does this beautifully. I composed a mail, clicked send and the very same moment unplugged the network cable. After about 8-10 seconds it shows a message "Oops... a server error occurred and your email was not sent."
The problem (2) above becomes more complicated on MAC. I checked this case on both MAC and Windows (I checked on windows XP). On windows XP if the network is not there, the request dies after few seconds but on MAC the request does not die for more than 1 hour. Here I can't think of a way to detect that network is gone while receiving response and show this notification to user?
$(window).ajaxError(function () {
alert('Oops. Server error occurred.');
});
or
error: function() { }
As a side note, all that's possible to know is if something failed or not. The browser doesn't know if the machine that's running it has internet access or if the cable gets pulled.... All it knows, and all you need to do, is handle the error cases through either this handler above or jquery's error function param in your AJAX call.
Also, for #2, the gmail error that's being shown is simply that your request wasn't sent successfully. It has nothing to do with server-side processes.
EDIT: For additional information (such as setting a timeout value that's shorter):
http://api.jquery.com/jQuery.ajaxSetup
Note that the accepted values for ajaxSetup
are those listed here:
http://api.jquery.com/jQuery.ajax
精彩评论