JQuery的阿贾克斯 - 让Ajax调用时如何检测网络连接错误 [英] JQuery Ajax - How to Detect Network Connection error when making Ajax call

查看:142
本文介绍了JQuery的阿贾克斯 - 让Ajax调用时如何检测网络连接错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些JavaScript JQuery的code,做一个Ajax调用服务器每5分钟,这是保持服务器会话存活并保持用户登录。我使用 $。阿贾克斯()方法JQuery的。这个功能似乎有一个'错误'的属性,我想在用户的网络连接断开,以便保持活动时间脚本继续运行的情况下使用。我用下面的code:

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:

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秒,这是好的。然而,当我拔掉网线,我什么也没得到,我期待误差函数被调用,并看到一个失败的提示框,但没有任何反应。

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.

我是正确的假设错误功能仅适用于CS从服务器返回非'200'的状态$ C $?有没有办法让一个Ajax调用时,检测到的网络连接问题吗?

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?

推荐答案

您应该只需要添加:超时:其中,毫秒&GT的数量;,地方在 $。阿贾克斯({})。 此外,缓存:假的,可能有助于在少数情况下

You should just add: timeout: <number of miliseconds>, somewhere within $.ajax({}). Also, cache: false, might help in a few scenarios.

$。阿贾克斯是有据可查的,您应检查选项出现,可能会发现一些有用的东西。

$.ajax is well documented, you should check options there, might find something useful.

祝你好运!

这篇关于JQuery的阿贾克斯 - 让Ajax调用时如何检测网络连接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆