我尝试执行两个连续的ajax请求,例如:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","data.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send('url=' + url);
var x=10;
var y=20;
xmlhttp.open("POST","datatest.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send('x=' + x, 'y=' + y);
不会出错,但会说:
POST http://dev01.dev/data.php Aborted
仅在datatest.php中显示echo
的结果。我可以从data.php和datatest.php获得响应吗?
更新:
data.php
会给出一些结果。
echo $result1;
datatest.php
会给出一些结果。
echo $result2;
我想在myDiv
上追加两个结果。
如果我这样做
document.getElementById("myDiv").innerHTML=xmlhttp.responseText1;
然后
document.getElementById("myDiv").innerHTML=xmlhttp.responseText2;
它将取代内容。我想追加它!
答案 0 :(得分:1)
我能从data.php和datatest.php获得响应吗?
使用单独的 XHR对象,而不是尝试重用现有对象。您当前的代码启动请求,但是在请求完成之前,您再次对同一个XHR对象执行xmlhttp.open("POST","datatest.php",true);
,因此会中止。
例如:
var xmlhttp1, xmlhttp2;
function getXHR() {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
else { // code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
xmlhttp1 = getXHR();
xmlhttp1.onreadystatechange = function () {
if (xmlhttp1.readyState == 4 && xmlhttp1.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp1.responseText;
}
};
xmlhttp1.open("POST", "data.php", true);
xmlhttp1.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp1.send('url=' + url);
var x = 10;
var y = 20;
xmlhttp2 = getXHR();
xmlhttp2.onreadystatechange = function () {
// Presumably do someething with the result of this one, too
};
xmlhttp2.open("POST", "datatest.php", true);
xmlhttp2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp2.send('x=' + x, 'y=' + y);