Javascript:检查服务器是否在线? [英] Javascript: Check if server is online?

查看:464
本文介绍了Javascript:检查服务器是否在线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What's the fastest way to check if my server is online via JavaScript?

我尝试过以下AJAX:

I've tried the following 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;
    }   
}

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

The problem is, it never returns if the server is offline. How can I set a timeout so that if it isn't returning after a certain amount of time, I can assume it is offline?

推荐答案

XMLHttpRequest 不支持跨域工作。相反,我会加载一个小的< img> ,你希望它能够快速返回并观看 onload 事件:

XMLHttpRequest does not work cross-domain. Instead, I'd load a tiny <img> that you expect to come back quickly and watch the onload event:

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加载解决方案最简单。没有必要混淆超时。如果你想使代码看起来就像是同步的,这里有一些对你的语法糖:

Cleaning up my answer. An XMLHttpRequest solution is possible on the same domain, but if you just want to test to see if the server is online, the img load solution is simplest. There's no need to mess with timeouts. If you want to make the code look like it's synchronous, here's some syntactic sugar for you:

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
});

这篇关于Javascript:检查服务器是否在线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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