欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ajax异步判断网站是否可以访问到的解决方法(XMLHttpRequest)

程序员文章站 2022-07-06 22:54:53
...
原文地址:https://www.cnblogs.com/lyl6796910/archive/2011/11/16/2461342.html

    function getXMLHttpRequest(){   
      var client = getXMLHttpRequestFromIE();   
       if(client == null){   
            client = new XMLHttpRequest();   
       }   
      return client;   
    }   
      
    function getXMLHttpRequestFromIE(){   
      var namePrefixes = ["Msxml3","Msxml2","Msxml","Microsoft"];   
      for(var i = 0; i < namePrefixes.length; i++){   
           try{   
               var name = namePrefixes[i] + ".XMLHTTP";   
               return new ActiveXObject(name);   
           }catch(e){   
           }   
      }   
      return null;   
    }   
    var client = null;   
    //是否可以访问   
    var isRun = false;   
    //返回值   
    var stateString="";   
    //请求url的网站   
    function connUrl(url){   
        client = getXMLHttpRequest();   
        var actionURL = convertURL(url);   
        try{   
            client.open("GET", actionURL, true);   
            client.onreadystatechange = callBack;   
            client.send(null);   
        }catch(e){}   
        finally{   
        }   
    }   
    function callBack(){   
        if(client.readyState == 4){   
            stateString = client.responseText;   
            if(stateString && client.status==200)   
                isRun = true;   
        }   
    }   
    //是否可达   
    function isReach(url){   
        connUrl(url);   
        return isRun;   
    }   
    //给url地址增加时间戳,骗过浏览器,不读取缓存       
    function convertURL(url) {       
            //获取时间戳       
            var timstamp = (new Date()).valueOf();       
            //将时间戳信息拼接到url上   
            if (url.indexOf("?") >= 0) {       
                    url = url + "&t=" + timstamp;       
            } else {       
                    url = url + "?t=" + timstamp;       
            }       
            return url;       
    }   
    //因为是异步,先调用,此时isRun的值是false   
    isReach("http://www.baidu.com");   
    //3秒钟后判断isRun的值,如果为false认为网站不可达,类似超时时间   
    setTimeout(function(){      
            //alert(stateString);    
            //alert(isRun);   
            if(isRun==true){   
                document.getElementById("ceshi").innerText = "网站是通的!";   
            }else{   
                document.getElementById("ceshi").innerText = "网站不通!";   
            }   
        },3000);  



<div id="ceshi"></div>  

相关标签: ajax html