首先来看一个实例:
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) + "×tamp=" + 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) + "×tamp=" + 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);
}
运行效果:
处理多个异步请求