Ajax 同一页面如何同时执行多个 XMLHTTP 呢,比如博客页,需要同时利用 Ajax 读取作者信息、文章信息、评论信息……

我们的第一反应可能是创建多个全局 XMLHTTP 对象,但这并不现实。其实实现方式非常简单,就是给 onreadystatechange 对应的回调函数加上参数,以下代码是解决方案中一个函数中的一段代码。

xmlhttp.open("GET""ajax_process.aspx?a=" + a, true);
xmlhttp.onreadystatechange 
= function () { OnReadyStateChng(xmlhttp, a); };
xmlhttp.send(
null);

只是改写 onreadystatechange 的属性值,这样就可以为 OnReadyStateChng 函数赋参数了。如是我们写作 xmlhttp.onreadystatechange = OnReadyStateChng;,那么 OnReadyStateChng 就不能有参数了,也就无法获得是哪个 xmlhttp 的响应,也就无法获得是响应后要对哪个控件进行设置。

我们可以看一个完整的示例,前台页面是普通的 Ajax 技术的 HTML 页面,后台使用的是 ASP.NET 的 .aspx 文件,之所以采用 ASP.NET,是为了演示延时处理功能。

前台程序


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<title>Ajax Test</title>

<script type="text/javascript" language="javascript">
<!--


// 1.创建XMLHttpRequest对象
function CreateHTTPObject()
{
    
var xmlhttp;
    
    
try
    
{
        xmlhttp 
= new ActiveXObject("Msxml2.XMLHTTP");
    }

    
catch (e)
    
{
        
try
        
{
            xmlhttp 
= new ActiveXObject("Microsoft.XMLHTTP");
        }

        
catch (e)
        
{
            xmlhttp 
= false;
        }

    }

    
    
if (!xmlhttp && typeof XMLHttpRequest!='undefined')
    
{
        
try
        
{
            xmlhttp 
= new XMLHttpRequest();
        }

        
catch (e)
        
{
            xmlhttp
=false;
        }

    }

    
    
if (!xmlhttp && window.createRequest)
    
{
        
try
        
{
            xmlhttp 
= window.createRequest();
        }

        
catch (e)
        
{
            xmlhttp
=false;
        }

    }

    
    
return xmlhttp;
}






// 2.浏览器 -> 服务器  (提交请求信息)
function SubmitMsg(a)
{
    
var xmlhttp = CreateHTTPObject();
    
//alert(xmlhttp);
    if (!xmlhttp)
    
{
        
return//无法创建 xmlhttp 对象
    }

    
//Ajax 提交   
            xmlhttp.open(
"GET""ajax_process.aspx?a=" + a, true);
    xmlhttp.onreadystatechange 
= function () { OnReadyStateChng(xmlhttp, a); };
    xmlhttp.send(
null);
}








// 3.服务器 -> 浏览器  (正确时返回数据)
function OnReadyStateChng(xmlhttp, a)
{
    
if (xmlhttp.readyState == 4)
    
{
        
if (xmlhttp.status == 200)
        
{
            document.getElementById(a).innerHTML 
= xmlhttp.responseText;
        }

        
else
        
{
            alert(
"HTTP 错误,状态码:" + xmlhttp.status);
        }

    }
 
    
else {//显示一个等待响应的图片
        document.getElementById(a).innerHTML 
= "<img src=tpl/1-0.gif align=absmiddle>";
    }

}



function loadall(){
SubmitMsg(
"a1");
SubmitMsg(
"a2");
SubmitMsg(
"a3");

}


-->
</script>

</head>
<body onload=loadall()>
<div id="a1" style="border:1px solid red;float:left">1</div>
<div id="a2" style="border:1px solid green;float:left">2</div>
<div id="a3" style="border:1px solid yellow">3</div>

</body>
</html>

后台程序

<%@ Page Language="C#" %>
<%Response.Expires = 0%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    
void Page_Load(object sender, EventArgs e)
    
{
        
if (Request.QueryString["a"== "a1")
        
{
            System.Threading.Thread.Sleep(
3000); //延时 3 秒
        }

        
else if (Request.QueryString["a"== "a2")
        
{
            System.Threading.Thread.Sleep(
1000); //延时 1 秒
        }

        
else if (Request.QueryString["a"== "a3")
        
{
            System.Threading.Thread.Sleep(
2000); //延时 2 秒
        }

    }

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>Ajax Test</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
    
    
</div>
    
</form>
</body>
</html>

演示解说

前台页面发出三个异步回送请求,分别为 a1、a2、a3 请求值,在后台页面中,通过延时模拟处理 a1 需要 3 秒,处理 a2 需要 1 秒,处理 a3 需要 2 秒。通过演示发现最先有变化的是 a2,然后是 a3、a1,顺序并没有乱,也没有出现显示混乱的情况。注意后台页面需要 Response.Expires = 0; 这么一句代码指示页面立即过期,否则刷新时请求的是缓存的页面,演示也就没有效果了。

另外

每个 xmlhttp 的 onreadystatechange 对应的函数名称也可以不同,不仅限于参数不同