Monday, February 07, 2005
xmlHttp Family
一般情况下xmlhttp的调用是:
var xh=new ActiveXObject("Microsoft.XMLHTTP");
xh.open("GET","http://localhost/quickstart/aspplus/doc/businessobjs.aspx",false);
xh.send("");
return xh.status == 200;
以上使用Microsoft.XMLHTTP。如果一个站点没有响应,他会一直等下去。改成Msxml2.ServerXMLHTTP就可以避免这个问题。参考蝈蝈俊的例子(http://blog.joycode.com/ghj/archive/2004/06/21/25186.aspx):
try
{
// 使用这个,可以设置超时时间,不用一直等待。
var xmlServerHttp = new ActiveXObject("Msxml2.ServerXMLHTTP");
var lResolve = 5 * 1000;
var lConnect = 5 * 1000;
var lSend = 15 * 1000;
var lReceive = 15 * 1000;
xmlServerHttp.setTimeouts(lResolve, lConnect, lSend, lReceive);
xmlServerHttp.open("GET", "http://localhost/quickstart/aspplus/doc/businessobjs.aspx", false);
xmlServerHttp.send();
return xmlServerHttp.status == 200;
}
catch( X )
{
return false;
}
如果要访问的页面是需要身份验证的。请参考:
oXMLHttpRequest.open(Method, Url, Async, User, Password)
http://www.w3schools.com/dom/dom_http.asp
Microsoft.XMLHTTP的“亲戚”不少,http://www.ph4nt0m.org的zzzEVAzzz <zzzevazzz@126.com> 列出:Msxml2.XMLHTTP、Msxml2.ServerXMLHTTP、Msxml2.DOMDocument、WinHttp.WinHttpRequest
Google Suggest的做法则是:
function jb(){
var A=null;
try{
A=new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e){
try{
A=new ActiveXObject("Microsoft.XMLHTTP")
}
catch(oc){
A=null
}
}
if(!A&&typeof XMLHttpRequest!="undefined"){
A=new XMLHttpRequest()
}
return A
}
XmlHttp异步获取网站数据的例子
<script>
var oDiv
var xh
function getXML()
{
oDiv = document.all.m
oDiv.innerHTML = "正在装载栏目数据,请稍侯......."
oDiv.style.display= ""
xh = new ActiveXObject("Microsoft.XMLHTTP")
xh.onreadystatechange = getReady
xh.open("GET",a.value,true)
xh.send()
}
function getReady()
{
if(xh.readyState==4)
{
if(xh.status==200)
{
oDiv.innerHTML = "完成"
}
else
{
oDiv.innerHTML = "抱歉,装载数据失败。原因:" + xh.statusText
}
}
}
</script>
<body>
xmlhttp异步的例子:
URL:<input name=a value="http://www.knowsky.com"... idth:600px">
<input onclick="getXML()" type="button" value="得到源代码">
<input onclick="if(xh && xh.responseText) {alert(xh.responseText);oDiv.innerHTML=xh.responseText}" type="button" value="显示源代码">
<div id=m></div>

