AJAX 处理多个异步请求
通常xmlHttp 异步对象我们都是用1个全局变量进行异步请求处理,这样做会存在一些问题。如:当第1个异步请求尚未完成,很可能就已经被第2个异步请求所覆盖。
解决办法:通常是将xmlHttp 对象作为局部变量来处理,并且在收到服务器端的返回值后手动将其删除。
事例:
function ReceiveMailOne(type){ var xmlHttp; try { xmlHttp = new XMLHttpRequest();//other browser } catch (trymicrosoft) { try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");//new ie } catch (othermicrosoft) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//old ie } catch (failed) { alert("<?php echo js_notsupport; ?>"); xmlHttp = false; } } } var url = "common/ajaxreceiveemlone.php?timestamp=" + new Date().getTime(); xmlHttp.open("POST", url); xmlHttp.onreadystatechange = function(){ if (xmlHttp.readyState ==4 && xmlHttp.status == 200){ CreateXML(sMessages); delete xmlHttp; //收到返回结果后手动删除 xmlHttp = null; } // setTimeout("clearserverResponse()",2000); } xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttp.send(null); }
调用:
for(var i=1;i<=3;i++){ ReceiveMailOne('checkone'); }
参考:
http://www.cnblogs.com/xugang/archive/2010/08/07/1794748.html
http://blog.csdn.net/liruxing1715/article/details/7162098