最近在弄js的XMLHttpRequest,如果不放在循环里面执行,效果很好,但是一放入循环,就出问题。只能改成同步,假死现象很明显。然后在网上查了很多资料,还是没什么弄清楚。有的说是闭包可以解决问题。有的说异步执行很多的话可能来不及返回。所以想求个例子,XMLHttpRequest放在for里面的例子,最好是js的。越详细越好。
解决方案 »
- 目前正在学习jquery中,请多多指教,请问下面这段代码那里出了问题,谢谢
- .net服务器控件 调用js(c#button与js结合问题)
- 滚动条事件触发解决办法
- javascript如果判断keyup事件前后value值是否有变化
- 用js,在提交一个form的时候,怎么控制弹出来窗口的大小啊?
- showModalDialog值的传递问题
- 高分,如何用javascript寫出類vb的ide的界面
- 老问题了,全加了,散了!
- 怎么判断一个Input type= text中的数字是不是浮点数?
- 请问怎样才能控制Iframe的height?
- 求救啊...关于cookie读取之后转换的问题.
- lang["abcd"]什么意思
<script>
function createXMLHttpRequest(){
http_request = false;
if(window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { http_request = false; }
}
}
return http_request;
}var xmlhttp = createXMLHttpRequest();
var n = 0;function doSend(){
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", "test1.asp", true);
xmlhttp.send(null);
}
function callback(){
if (xmlhttp.readyState == 4){
if (xmlhttp.status == 200){
alert(xmlhttp.responseText);
n--;
if(n>0) doSend();
}
}
}
function startReq(){
n = 4 // 循环次数;
doSend()
}
</script>
<input type="button" value="START" onclick ="startReq();">
var net=new Object();net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;
/*--- content loader object for cross-browser requests ---*/
net.ContentLoader=function(url,onload,onerror,method,params,contentType){
this.req=null;
this.onload=onload;
this.onerror=(onerror) ? onerror : this.defaultError;
this.loadXMLDoc(url,method,params,contentType);
}net.ContentLoader.prototype={
loadXMLDoc:function(url,method,params,contentType){
if (!method){
method="GET";
}
if (!contentType && method=="POST"){
contentType='application/x-www-form-urlencoded';
}
if (window.XMLHttpRequest){
this.req=new XMLHttpRequest();
} else if (window.ActiveXObject){
this.req=new ActiveXObject("Microsoft.XMLHTTP");
}
if (this.req){
try{
var loader=this;
this.req.onreadystatechange=function(){
loader.onReadyState.call(loader);
}
this.req.open(method,url,true);
if (contentType){
this.req.setRequestHeader('Content-Type', contentType);
}
this.req.send(params);
}catch (err){
this.onerror.call(this);
}
}
}, onReadyState:function(){
var req=this.req;
var ready=req.readyState;
var httpStatus=req.status;
if (ready==net.READY_STATE_COMPLETE){
if (httpStatus==200 || httpStatus==0){
this.onload.call(this);
}else{
this.onerror.call(this);
}
}
}, defaultError:function(){
alert("error fetching data!"
+"\n\nreadyState:"+this.req.readyState
+"\nstatus: "+this.req.status
+"\nheaders: "+this.req.getAllResponseHeaders());
}
}这样用,自己传callback函数就OK