方法一:(jQuery方法: 適用所有浏覽器)
HTML頁面:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script> </head> <body> <a href="http://www.baidu.com/">【jquery檢測鏈接有效性】</a> <a href="www.baidu.com/">【jquery檢測鏈接有效性2】</a> //<script type="text/javascript" src="js/base.js"></script> </body> </html>
JS頁面:
//判斷地址有效性
$("body a").each(function(){
$(this).click(function(){
$.ajax({
url: $(this).attr("href"),
type: 'GET',
complete: function(response){
if(response.status == 404){
location.href="http://www.baidu.com/404.html";
alert('無效');
}else{
alert('有效');
}
}
});
});
});
方法二:(AJAX XMLHTTP方法: 使用ActiveXObject,所以僅支持IE,非IE內核浏覽器不可用。)
<script type="text/javascript">
function chkurl(url) {
var xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP");
xmlhttp.open("GET",url,false);
xmlhttp.send();
if(xmlhttp.readyState==4){
if(xmlhttp.Status != 200) alert("不存在")
else alert("存在")
}
}
</script>
<a href="http://www.baidu.com/" onclick="javascript:return chkurl(this.href);">【ajax檢測鏈接有效性】</a>
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持!