我需要一个单击一个链接的函数,将ajax请求逐个发送到2个页面。
首先将数据发送到page1.php
,当完成page1的工作时,将数据返回到主页面,然后将数据发送到page2.php
做另一个ajax进程并将数据返回到主页面。
我在page2.php
page1.php
中写了document.getElementById("div1").innerHTML = HttPRequest.responseText;
个请求,但这只会返回page2's
数据,并会错过page1.php
在firebug
中,消费者:
page1.php (always show loading.gif)
page2.php 200 OK 2199ms
如何一个接一个地做ajax?感谢。
function myajax(text) {
var HttPRequest = false;
if (window.XMLHttpRequest) {
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 'page1.php';
var pmeters = "text=" + text;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 4)
{
document.getElementById("div1").innerHTML = HttPRequest.responseText;
var url = 'page2.php';
var pmeters = "text=" + text;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 4)
{
document.getElementById("div2").innerHTML = HttPRequest.responseText;
}
}
}
}
}
答案 0 :(得分:0)
有两种选择。
选项2更好,因为它在异步模式下工作。
这是一个伪代码:
var xhr = new XMLHttpRequest();
xhr.open( ..)
xhr.onreadstatechange = function() {
// handle page1 response
// do page2 reauest
var xhr2 = new XMLHttpRequest();
xhr2.open( ... )
xhr2.onreadystatechange = function() {
// handle page2 response
}
xhr2.send(null);
}
xhr.send(null);