AJAX学习笔记之 处理多个异步请求

首先来看一个实例:

 

9-5.html:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>多个异步对象</title>
<script language="javascript">
var xmlHttp; //全局变量 
function createQueryString(oText){
 var sInput = document.getElementById(oText).value;
 var queryString = "oText=" + sInput;
 return queryString;
}
function getData(oServer, oText, oSpan){
 if(window.ActiveXObject)
  xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
 else if(window.XMLHttpRequest)
  xmlHttp = new XMLHttpRequest();
 var queryString = oServer + "?";
 queryString += createQueryString(oText) + "&timestamp=" + new Date().getTime();
 xmlHttp.onreadystatechange = function(){
  if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
   var responseSpan = document.getElementById(oSpan);
   responseSpan.innerHTML = xmlHttp.responseText;
  }
 }
 xmlHttp.open("GET",queryString);
 xmlHttp.send(null);
}
function test(){
 //同时发送两个不同的异步请求
 getData('9-5.aspx','first','firstSpan');
 getData('9-5.aspx','second','secondSpan');
}
</script>
</head>

<body>
<form>
 first: <input type="text" id="first">
 <span id="firstSpan"></span>
<br>
 second: <input type="text" id="second">
 <span id="secondSpan"></span>
<br>
 <input type="button" value="发送" οnclick="test()">
</form>
</body>
</html>

 

9-5.aspx:

 

<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" %>
<%@ Import Namespace="System.Data" %>
<%
 Response.Write(Request["oText"]);
%>

 

运行效果:

第一个请求被覆盖

                    第一个请求被覆盖

 

 

出现这个问题是xmlHttp被作为一个全局变量而存在,第一个请求未完成,已经被之后的请求所覆盖。

解决方法是将xmlHttp对象作为局部变量来处理,并且在收到服务器的返回值后手动将其删除。

修改getData()代码如下:

 

 

function getData(oServer, oText, oSpan){
 var xmlHttp; //处理为局部变量
 if(window.ActiveXObject)
  xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
 else if(window.XMLHttpRequest)
  xmlHttp = new XMLHttpRequest();
 var queryString = oServer + "?";
 queryString += createQueryString(oText) + "&timestamp=" + new Date().getTime();
 xmlHttp.onreadystatechange = function(){
  if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
   var responseSpan = document.getElementById(oSpan);
   responseSpan.innerHTML = xmlHttp.responseText;
   delete xmlHttp;  //收到返回结构后手动删除
   xmlHttp = null;
  }
 }
 xmlHttp.open("GET",queryString);
 xmlHttp.send(null);
}

 

运行效果:

              处理多个异步请求

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值