Is it possible to ping a server from Javascript?

后端 未结 17 904
礼貌的吻别
礼貌的吻别 2020-11-22 04:02

I\'m making a web app that requires that I check to see if remote servers are online or not. When I run it from the command line, my page load goes up to a full 60s (for 8 e

17条回答
  •  粉色の甜心
    2020-11-22 04:49

    If what you are trying to see is whether the server "exists", you can use the following:

    function isValidURL(url) {
        var encodedURL = encodeURIComponent(url);
        var isValid = false;
    
        $.ajax({
          url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
          type: "get",
          async: false,
          dataType: "json",
          success: function(data) {
            isValid = data.query.results != null;
          },
          error: function(){
            isValid = false;
          }
        });
    
        return isValid;
    }
    

    This will return a true/false indication whether the server exists.

    If you want response time, a slight modification will do:

    function ping(url) {
        var encodedURL = encodeURIComponent(url);
        var startDate = new Date();
        var endDate = null;
        $.ajax({
          url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
          type: "get",
          async: false,
          dataType: "json",
          success: function(data) {
            if (data.query.results != null) {
                endDate = new Date();
            } else {
                endDate = null;
            }
          },
          error: function(){
            endDate = null;
          }
        });
    
        if (endDate == null) {
            throw "Not responsive...";
        }
    
        return endDate.getTime() - startDate.getTime();
    }
    

    The usage is then trivial:

    var isValid = isValidURL("http://example.com");
    alert(isValid ? "Valid URL!!!" : "Damn...");
    

    Or:

    var responseInMillis = ping("example.com");
    alert(responseInMillis);
    

提交回复
热议问题