jQuery/AJAX:如何确定主机何时脱机

ssh*_*ksh 5 php ajax jquery

我有一个jQuery脚本,用于轮询我的服务器以获取新数据,但如果因任何原因失败,则需要显示错误消息.

这是我的AJAX请求:

$.ajax({
    url: "query.php", // This just runs some MySQL queries and echos the results
    cache: false,
    error: function() {
       $(".status").text("Server is offline.");
       },
    success: function(html) {
       // Everything went fine, append query results to div
       }
});
Run Code Online (Sandbox Code Playgroud)

我发现如果重命名query.php使其无法访问,则会触发错误功能并显示消息.但是,如果我使Web服务器脱机,则不会触发错误功能.

如何调整代码以检测主机何时无法访问?

Sar*_*rke 2

您应该设置一个较低的超时时间,需要注意的是,成功仍然会被调用,因此您必须检查此时是否有任何数据,以了解是否超时。

.ajax({
    url: "query.php", // This just runs some MySQL queries and echos the results
    cache: false,
    timeout: 4000, // 4 seconds
    error: function() {
       $(".status").text("Unable to retrieve data.");
       },
    success: function(html) {
       if (html) {
           // Everything went fine, append query results to div
       }
       else {
           $(".status").text("Server is offline.");
       }
});
Run Code Online (Sandbox Code Playgroud)