Ajax不一致的超时行为

时间:2014-02-18 02:34:34

标签: javascript jquery ajax

我有一个网络应用程序,我添加了一个简单的ajax调用来提供网络连接状态。它按预期工作,具有良好的连接,问题是它何时失败。

我正在使用osx网络链路调节器(nlc)来模拟连接错误。我希望当我增加nlc中的延迟时ajax请求需要更长的时间,直到它应该超时的30秒。有时我确实看到它按预期超时,有时它会提前失败(例如18秒,但我仍然期望它会达到30秒)。错误消息也无济于事,它只是说“错误”。

行为不一致所以很难确定正在发生的事情。它托管在一个apache服务器上,我将保持活动超时更改为60秒,所以这应该是充足的。

<!DOCTYPE html>
<html>
<head>
    <title>Ping test</title>
</head>
<body>
<a href="" onclick= "checkNetworkStatus(); return false;">Ping test!</a>

<script type="text/javascript" src="libs/jquery-2.1.0.min.js"></script>
<script type="text/javascript">

function checkNetworkStatus() {
    // Time how long the call to the server takes
    var start_time = new Date().getTime();

    if (navigator.onLine) {
        $.ajax({
            async: true,
            cache: false,
            dataType: "json",
            error: function (request, status, err) {
                console.log("request:" + request + " status:" + status + " err:" + err);

                // Measure data gathering time
                var request_time = new Date().getTime() - start_time;
                console.log(request_time);
            },
            success: function (data, status, req) {
                console.log("Ping success!");

                // Measure data gathering time
                var request_time = new Date().getTime() - start_time;
                console.log(request_time);
            },
            timeout: 30000,
            type: "GET",
            url: "js/ping.js"
        });

    }
    else {
        console.log("Not connected to network!");
    }
}

</script>
</body>
</html>

ping.js就是这样:

{ "status": "Online" }

与此问题类似jQuery ajax txtStat does not return "timeout" but "error"但在我的情况下,连接速度从未完全关闭。

0 个答案:

没有答案