你能在打开窗口之前先检查一下服务器吗

Can you check a server before doing a window.location change?

本文关键字:一下 服务器 检查 开窗口      更新时间:2023-11-21

我主要需要做的是window.location = http://myserver.com,它带有一个条件语句,说明如果你可以连接到此服务器,那么就去做,否则就留在当前窗口。location并提示一条消息,说你无法连接。

通过测试您的服务器(假设它与您所在的域相同,否则它将抛出一个允许原点而不是null或其他什么)是否已启动来进行检查:

function hasInternets() {
    console.log("hasInternets: " + window.location.href.split("?")[0] + "?" + Math.random());
    var s = $.ajax({ 
        type: "HEAD",
        url: window.location.href.split("?")[0] + "?" + Math.random(),
        async: false
    }).status;
        console.log("s: " +s);
    //thx http://www.louisremi.com/2011/04/22/navigator-online-alternative-serverreachable/
    return s >= 200 && s < 300 || s === 304; }