Ajax+JS判断页面是否存在

本文介绍了一种利用JavaScript中的XMLHttpRequest对象来检测网页是否存在及其状态的方法。通过发送GET请求并监听onreadystatechange事件,可以判断目标网址是否可达,并根据HTTP响应状态码来确定页面的状态。
<html>  
    <head>  
        <title>My JSP 'a.jsp' starting page</title>  
   <script language="javascript">       
    var xmlHttp= null;  
       //判断浏览器
        function createXMLHttpRequest() {
            if (window.XMLHttpRequest) {
                //Firefox,Netscape,Chrome,Safari等浏览器
                xmlHttp = new XMLHttpRequest();
            } else if (window.ActiveXObject) { //IE浏览器
                try {
                    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); //创建xmlHttp对象
                } catch (e) {
                    try {
                        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //创建xmlHttp对象
                    } catch (e) { }
                }
            }
        }
     function   GetURL(url){     
   	  createXMLHttpRequest();  
  	  xmlHttp.open("GET",url,true);  
          xmlHttp.send(null); 
          xmlHttp.onreadystatechange = function(){  
                 if(xmlHttp.readyState==4){  
                    if(xmlHttp.status==200){  
                        alert("页面存在");  
                    }else {  
                        alert("页面不存在");  
                    }  
                  }  
          }   
  }     
  
  </script>  
    </head>  
  
    <body>  
        <input type="button" onclick="GetURL('http://www.google.com')"  
            value="该页面存在">  
        <input type="button"  
            onclick="GetURL('http://www.error.com/error.html')" value="此页面不存在"></input>  
    </body>  
</html>  


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值