javascript – JQuery Ajax – 如何在进行Ajax调用时检测网络连接错误
问题:
我有一些Javascript JQuery代码每隔5分钟对服务器进行一次Ajax调用,这是为了保持服务器会话的存活并保持用户登录。我在JQuery中使用$.ajax()
方法。 这个函数似乎有一个’错误’属性,我试图在用户的互联网连接断开时使用,以便KeepAlive脚本继续运行。 我正在使用以下代码:
var keepAliveTimeout = 1000 * 10;
function keepSessionAlive()
{
$.ajax(
{
type: 'GET',
url: 'http://www.mywebapp.com/keepAlive',
success: function(data)
{
alert('Success');
setTimeout(function()
{
keepSessionAlive();
}, keepAliveTimeout);
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Failure');
setTimeout(function()
{
keepSessionAlive();
}, keepAliveTimeout);
}
});
}
当我运行它时,我会在屏幕上每10秒钟在一个警告框中弹出“成功”,这很好。 但是,一旦我拔下网线,我就什么也得不到,我期待错误功能被调用并看到“故障”警告框,但没有任何反应。
假设’错误’功能仅适用于从服务器返回的非’200’状态代码,我是否正确? 有没有办法在进行Ajax调用时检测网络连接问题?
I have some Javascript JQuery code that does an Ajax call to the server every 5 mins, it’s to keep the server session alive and keep the user logged in. I’m using $.ajax()
method in JQuery.This function seems to have an ‘error’ property that I’m trying to use in the event that the user’s internet connection goes down so that the KeepAlive script continues to run.I’m using the following code:When I run it, I’ll get ‘Success’ popup on the screen in an alert box every 10 seconds which is fine.However, as soon as I unplug the network cable, I get nothing, I was expecting the error function to get called and see a ‘Failure’ alert box, but nothing happens.Am I correct in assuming that the ‘error’ function is only for non ‘200’ status codes returned from the server?Is there a way to detect network connection problems when making an Ajax call?