简体   繁体   English

使用AJAX检查远程站点是否在线?

[英]Check if a remote site is online using AJAX?

My site checks 5 different URLs using PHP's cURL to tell if they're online. 我的网站使用PHP的cURL检查5个不同的URL,以判断它们是否在线。 The problem is that it takes too long to load the page (especially if one of the sites it's checking is down). 问题是加载页面需要很长时间(特别是如果其中一个站点正在检查已关闭)。

I hear jQuery's ajax would work well, so I tried this code: 我听说jQuery的ajax运行良好,所以我尝试了这段代码:

<div class="alert alert-info" id="forum-blockland-us"><b>Checking...</b></div>
<script>
$.ajax({ type: "GET",
    url: "http://forum.blockland.us/",
    cache:false,
    success: function() { 
        $("#forum-blockland-us").addClass("alert-success");
        $("#forum-blockland-us").removeClass("alert-info");
        $("#forum-blockland-us").html("<b>Online</b>");
    },
    error: function() {
        $("#forum-blockland-us").addClass("alert-danger");
        $("#forum-blockland-us").removeClass("alert-info");
        $("#forum-blockland-us").html("<b>Offline</b>");
    }
});
</script>

But it always returns the error, even when I know 100% that the sites are online. 但它总是会返回错误,即使我100%知道这些网站是在线的。

If the site is remote, there are many chances you won't be able to achieve it with javascript due to the Same Origin Policy . 如果网站是远程的,也有因多的机会,你将不能够使用JavaScript来实现它同源策略

However, in php, you could make only a HEAD request so it doesn't load contents so it will be much, much faster. 但是,在php中,你只能生成一个HEAD请求,因此它不会加载内容,所以它会更快,更快。

Hope this helps. 希望这可以帮助。 Cheers 干杯

As @Edgar said, you better do it by php, and if you want to, this is how : 正如@Edgar所说,你最好通过php来做,如果你愿意,这是如何:

function urlExists($url=NULL)  
{  
    if($url == NULL) return false;  
    $ch = curl_init($url);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
    $data = curl_exec($ch);  
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
    curl_close($ch);  
    if($httpcode>=200 && $httpcode<300){  
        return true;  
    } else {  
        return false;  
    }  
}

Source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM