因为XMLHTTP组件太智能,会自动路过重定向,所以这里用WinHttp 检测:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>检测URL是否存在</title>
<SCRIPT LANGUAGE="JavaScript">
function check(str){
str = str.match(/http:\/\/.+/);
if (str == null){
alert('你输入的URL无效');
return false;
}else{
//alert("你输入的URL有效");
return true;
}
}
function getUrl()
{
var url = document.getElementById("url_input").value;
if (check(url))
{
isExist(url);
}
}
function isExist(url) {
//xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
xmlhttp = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
xmlhttp.Option(6)=0 //'禁止自动Redirect,最关键(的) 剩下(的)就简单读取数据都估计大家都会
xmlhttp.open("GET",url,false)
xmlhttp.send()
if(xmlhttp.status==200)
url += "存在";
else if(xmlhttp.status==301 || xmlhttp.status==302)
url += " 已重定向到: "+xmlhttp.getResponseHeader("Location");
else
url += "不存在";
document.getElementById("info_show").innerHTML = "<hr><pre><font color=red>"+xmlhttp.ResponseBody
+"URL:"+url+"<br><br>"+"Status:"+xmlhttp.Status+"<br>"+xmlhttp.getAllResponseHeaders()+"</font></pre>"
}
</SCRIPT>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<label>网址:
<input type="text" id="url_input" value="http://" size="80" />
</label>
<input name="button" type="button" onclick="getUrl()" value="检测URL" />
</form>
<div id="info_show"></div>
</body>
</html>