Javascript (Ajax)给XMLHttpRequest设置超时时间

by Admin3. March 2010 13:19

文章来源:疯狂代码
在Web开发中,经常要用到Ajax技术,有时因为功能很简单,不想利用现成的框架,就只是想利用XMLHttpRequest来手动处理Ajax功能,这时,会遇到一个很现实的问题,就是Ajax请求的超时问题。如果我们利用Jquery这样的框架,是可以直接设定超时时间的,但是XMLHttpRequest对象并没有设置超时的属性,怎么办呢?总不能让页面一直请求吧?@_@
下面是一种解决方法,就是利用setTimeout和clearTimeout方法,思路如下:在调用XMLHttpRequest的send方法后,调用setTimeout方法,设置超时时间值。在调用成功的方法内,调用clearTimeout()方法清除超时设置。

 

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',
'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0',
'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;
}
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);
}
}
//使用举例
var xmlhttp = createXMLHttpRequest();
var t1; //用来作超时处理
function adduserok(request) {
alert(request.responseText);
if (t1) clearTimeout(t1);
}
function connecttoFail() {
if (xmlhttp) xmlhttp.abort();
alert ('Time out');
}
if (xmlhttp) {
    ajax(xmlhttp,"POST", "http://www.loxiu.com/adduser.cgi","act=do&user=abc",adduserok);
    
t1 = setTimeout(connecttoFail,30000);
}
else {
    alert ("Init 
xmlhttprequest 
fail");
}

最后说明一点,手动处理Ajax功能,比较适合刚开始接触Ajax时用来学习Ajax的原理。要是想在项目中应用Ajax功能,还是选一个框架使用比较方便,在这里推荐一下jquery,真的很好用哟!@_@

Tags: , ,

JS

Comments (4) -

超级兔子
超级兔子People's Republic of China
3/3/2010 7:28:56 PM #

JS我如果几天不写马上就忘了

Reply

zhang4543
zhang4543People's Republic of China
3/3/2010 7:34:46 PM #

@超级兔子 靠,你真迅速....是不是一直在xss我呢

Reply

zhang4543
zhang4543
3/4/2010 12:10:33 AM #

评论时间错乱问题终于解决...
将DbBlogProvider.cs的
dpCommentDate.Value = comment.DateCreated;

改成
dpCommentDate.Value = comment.DateCreated.AddHours(-BlogSettings.Instance.Timezone);

Reply

Windshield Repair MN
Windshield Repair MNUnited States
10/14/2011 1:27:49 AM #

Great! This is what I am looking for, I will try out now, Thanks for posting!

Reply

Add comment

  Country flag

biuquote
Loading

我的饭否

Widget RandomPosts not found.

The file '/blog/widgets/RandomPosts/widget.ascx' does not exist.X

RecentComments

Comment RSS

Google PageRank