关于xmlhttp获取状态码404的判断

liyang36939 2011-06-06 11:06:34
我做的网页上引用一个链接,链接为其他网站的一个页面,我用的xmlhttp,如果链接的那个网页不存在,则跳转到另一个页面,我在自己的本机上的服务器测试是成功的,也是说那个链接是我本机服务器的一个页面,但是链接到其他网站的页面就会出错,现贴出程序
<http>
<head>
<script language="JavaScript">
var XMLHttpReq;
var url;
function createXMLHttpRequest(){
if(window.XMLHttpRequest){
XMLHttpReq=new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
XMLHttpReq=new ActiveXObject("Msxml2.XMLHTTP");

}catch(e){
try{
XMLHttpReq=new ActiveXObject("Microsoft.XMLHTTP");

}catch(e){}
}
}
}
function sendRequest(ur){
url=ur;
createXMLHttpRequest();
XMLHttpReq.open("GET",url,true);
XMLHttpReq.onreadystatechange=processResponse;
XMLHttpReq.send(null);
}
function processResponse(){
if(XMLHttpReq.readyState==4){
if(XMLHttpReq.status==200){
window.open(url,"_blank");

}else if(XMLHttpReq.status==404){
window.open("info.html","_blank");

}
}
}

</script>


</head>
<body>
<a href="test1.html" target="_blank">示例1</a>
<a href="" onclick="sendRequest('http://www.baidu.com')">example2</a>
</body>
</html>
info.html是页面不存在所要跳转的页面,example2里就是要访问的外部网页,baidu只是测试一下。
请教,帮我看一下,有什么错误?或者提供给我一个新的方法。小弟不甚感激。
...全文
304 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wcwtitxu 2011-06-07
  • 打赏
  • 举报
回复
以 asp 为例


queryStatus.asp
var u = Request.QueryString("u").Item || '';

if (u != "") {
try {
var x = Server.CreateObject("MSXML2.XMLHTTP");
x.open("GET", u, false);
x.send(null);
Response.Status = x.status + " " + x.statusText;
} catch(e) {
Response.Status = "400 Bad request"
}
} else {
Response.Status = "404 Not found.";
}




客户端
<html>
<head>
<script language="JavaScript">
var XMLHttpReq;
var url;

function createXMLHttpRequest(){
if(window.XMLHttpRequest){
XMLHttpReq=new XMLHttpRequest();
}else if(window.ActiveXObject){
try{
XMLHttpReq=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
XMLHttpReq=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
}

function sendRequest(ur){
createXMLHttpRequest();
XMLHttpReq.open("GET", "queryStatus.asp?u=" + encodeURIComponent(ur), true);
XMLHttpReq.onreadystatechange=processResponse;
XMLHttpReq.send(null);
}

function processResponse(){
if(XMLHttpReq.readyState==4){
if(XMLHttpReq.status==200){
window.open(url,"_blank");

}else if(XMLHttpReq.status==404){
window.open("info.html","_blank");

}
}
}
</script>


</head>
<body>
<a href="test1.html" target="_blank">示例1</a>
<a href="" onclick="sendRequest('http://www.baidu.com')">example2</a>
</body>
</html>
liyang36939 2011-06-06
  • 打赏
  • 举报
回复
1楼的可否告知下具体怎么操作
liyang36939 2011-06-06
  • 打赏
  • 举报
回复
2楼 但是如果远程页面不存在,怎么取到本地域
汉尼拔 2011-06-06
  • 打赏
  • 举报
回复
你需要用后台语言,先把东西取到本地域
wcwtitxu 2011-06-06
  • 打赏
  • 举报
回复
xmlhttp 不能跨域发出请求的。。。

所以你无法判断其它网站的页面是否 404

可考虑服务端代理一下

87,989

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧