Javascript:检查服务器是否在线?

时间:2011-03-07 19:25:00

标签: javascript

检查我的服务器是否通过JavaScript在线的最快方法是什么?

我尝试过以下AJAX:

function isonline() {
    var uri = 'MYURL'
    var xhr = new XMLHttpRequest();
    xhr.open("GET",uri,false);
    xhr.send(null);
    if(xhr.status == 200) {
        //is online
        return xhr.responseText;
    }
    else {
        //is offline
        return null;
    }   
}

问题是,如果服务器脱机,它永远不会返回。如何设置超时,以便如果在一段时间后没有返回,我可以假设它处于脱机状态?

5 个答案:

答案 0 :(得分:26)

XMLHttpRequest无法跨域工作。相反,我会加载一个很小的<img>,您希望快速返回并观看onload事件:

function checkServerStatus()
{
    setServerStatus("unknown");
    var img = document.body.appendChild(document.createElement("img"));
    img.onload = function()
    {
        setServerStatus("online");
    };
    img.onerror = function()
    {
        setServerStatus("offline");
    };
    img.src = "http://myserver.com/ping.gif";
}

修改:清理我的答案。在同一个域上可以使用XMLHttpRequest解决方案,但如果您只想测试服务器是否在线,则img加载解决方案最简单。没有必要混淆超时。如果你想使代码看起来像是同步的,那么这里有一些语法糖:

function ifServerOnline(ifOnline, ifOffline)
{
    var img = document.body.appendChild(document.createElement("img"));
    img.onload = function()
    {
        ifOnline && ifOnline.constructor == Function && ifOnline();
    };
    img.onerror = function()
    {
        ifOffline && ifOffline.constructor == Function && ifOffline();
    };
    img.src = "http://myserver.com/ping.gif";        
}

ifServerOnline(function()
{
    //  server online code here
},
function ()
{
    //  server offline code here
});

答案 1 :(得分:1)

以下是我使用Fetch管理请求以及AbortController在Node.js应用程序中处理超时来检查服务器可用性的方法。

&#13;
&#13;
function checkServer(url, timeout) {
  const controller = new AbortController();
  const signal = controller.signal;
  const options = { mode: 'no-cors', signal };
  return fetch(url, options)
    .then(setTimeout(() => { controller.abort() }, timeout))
    .then(response => console.log('Check server response:', response.statusText))
    .catch(error => console.error('Check server error:', error.message));
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用XMLHttpRequest,然后检查是否失败。不确定这是否适用于跨域。

答案 3 :(得分:0)

进行ajax调用,其结果将告诉你。

答案 4 :(得分:0)

添加到gilly3答案

在实践中,我发现有必要使用 Selection.Find.ClearFormatting With Selection.Find .Text = "MyTest" .Replacement.Text = "" .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchByte = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False End With Selection.Find.Execute 非常慢

尽管问题是关于纯JavaScript的,但使用一些HTML可以使该解决方案更快。

所以我将这段代码留给任何寻求速度的人。

document.body.appendChild