在Web开发中,经常要用到Ajax技术,有时因为功能很简单,不想利用现成的框架,就只是想利用XMLHttpRequest来手动处理Ajax功能,这时,会遇到一个很现实的问题,就是Ajax请求的超时问题。如果我们利用Jquery这样的框架,是可以直接设定超时时间的,但是XMLHttpRequest对象并没有设置超时的属性,怎么办呢?总不能让页面一直请求吧?@_@
下面是一种解决方法,就是利用setTimeout和clearTimeout方法,思路如下:在调用XMLHttpRequest的send方法后,调用setTimeout方法,设置超时时间值。在调用成功的方法内,调用clearTimeout()方法清除超时设置。
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
function createXMLHttpRequest() {
var request = false;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
if(request.overrideMimeType) {
request.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject) {
var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP',
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0',
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
for(var i=0; i<versions.length; i++) {
try {
request = new ActiveXObject(versions[i]);
if(request) {
return request;
}
} catch(e) {}
}
}
return request;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
function ajax(xmlhttp,_method, _url, _param, _callback) {
if (typeof xmlhttp == 'undefined') return;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
_callback(xmlhttp);
}
}
xmlhttp.open(_method, _url, true);
if (_method == "POST") {
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-Length", _param.length);
xmlhttp.send(_param);
}
else {
xmlhttp.send(null);
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
//使用举例
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
var xmlhttp = createXMLHttpRequest();
var t1; //用来作超时处理
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
function adduserok(request) {
alert(request.responseText);
if (t1) clearTimeout(t1);
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
function connecttoFail() {
if (xmlhttp) xmlhttp.abort();
alert ('Time out');
}
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
if (xmlhttp) {
ajax(xmlhttp,"POST", "http://10.1.2.187/adduser.cgi","act=do&user=abc",adduserok);
t1 = setTimeout(connecttoFail,30000);
}
else {
alert ("Init xmlhttprequest fail");
}
最后说明一点,手动处理Ajax功能,比较适合刚开始接触Ajax时用来学习Ajax的原理。要是想在项目中应用Ajax功能,还是选一个框架使用比较方便,在这里推荐一下jquery,真的很好用哟!@_@