What's the best way to check if a website is up or not via JavaScript

前端 未结 5 1227
情深已故
情深已故 2020-12-03 04:00

What is the best way to check if a site is up and running or down with JavaScript?

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 04:29

    Ajax alone might not be the answer - if you're trying to check a remote server, since by default you can't access a remote server via ajax.

    You can however access the server that the script resides/lives on - which means you can create some kind of script that acts as a proxy e.g. server side script that checks if the site in question is active and call that script via your ajax call.

    An example (PHP/C# & VB.Net) of how to do this: http://www.cstruter.com/articles/article/2/8

    As for Checking the status of the server:

    C#

            string URL = "http://www.stackoverflow.com";
        WebRequest request = WebRequest.Create(URL);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        //if (response.StatusCode == HttpStatusCode.something
    

    PHP

        @$headers = get_headers($url);
    

    return (preg_match('/^HTTP\/\d.\d\s+(200|301|302)/', $headers[0]));

提交回复
热议问题