今天在使用xmlhttprequest时候碰到个问题,ie一直报错误。
会提示你:“未指定的错误!”
仔细查看原来是很弱的问题。
status
服务器的HTTP状态码(200对应OK,404对应Not Found(未找到),等等)
readyState
请求的状态。有5个可取值:0 = 未初始化,1 = 正在加载,2 = 已加载,3 = 交互中,4 = 完成
<!--
var request;
var url = ' http://video.qq.com/bin/vrank?type=8&Start=1&end=199 ' ;
// try {
request = new ActiveXObject( " Microsoft.XMLHTTP " );
request.open( " GET " , url, false );
request.onreadystatechange = function () ... {
if(request.readyState == 4 && request.status == 200)...{
//if(){
alert("success!");
//}
}
}
request.send( null );
// -->
</ script >
还是进行优化下这个吧。
主要是xmlHttpRequest创建上,要适应不同的浏览器,不同版本的IE。就需要改造下这个脚步。
在wrox网站上看到篇文章【http://www.wrox.com/WileyCDA/Section/id-291289.html
上面有段介绍是:
This line creates the first version of the XMLHttp object (the one shipped with IE 5.0). The problem is that there have been several new versions released with each subsequent release of the MSXML library. Each release brings with it better stability and speed, so you want to make sure you are always using the most recent version available on the user's machine. The signatures are:
Microsoft.XMLHttp
MSXML2.XMLHttp
MSXML2.XMLHttp.3.0
MSXML2.XMLHttp.4.0
MSXML2.XMLHttp.5.0
也就是说,不同版本的IE浏览器使用了不同的activeX对象,当然,越是最新的版本,其效率将更好,但是我们并不能保证客户端都装了最新的IE,所以,就要使用循环测试的办法了。
修改后的脚本为:
<!--
function createXMLHttp() ... {
if (typeof XMLHttpRequest != "undefined") ...{ // 非IE
return new XMLHttpRequest();
} else if (window.ActiveXObject) ...{ // IE浏览器
var aVersions = [ "MSXML2.XMLHttp.5.0",
"MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
"MSXML2.XMLHttp","Microsoft.XMLHttp"
];
for (var i = 0; i < aVersions.length; i++) ...{
try ...{
var oXmlHttp = new ActiveXObject(aVersions[i]);
return oXmlHttp;
} catch (oError) ...{
//Do nothing
}
}
}
throw new Error("XMLHttp object could be created.");
}
function getXmlHttp(url) ... {
try
...{
request.open("GET", url, true); // true:异步;false:同步;
request.onreadystatechange = function()...{
if (request.readyState == 4)...{
//alert(request.status);
if (request.status == 200)...{
// 请求并成功返回
}
}
else
connectToNet = false;
}
request.send(null);
}
catch (ex)...{connectToNet = false;}
}
// -->
</ SCRIPT >