这是我的JS代码。但是,它只执行了最后一个 ajax 请求。无论如何可以将它们放在 If 语句中,以便
如果(主内容.html被加载),它将执行xmlhttp.open("GET","main-content-city.php?q="+str,true)
xmlhttp.send();
elseif(加载子内容),执行:xmlhttp.open("GET","child-content-city.php?q="+str,true);
xmlhttp.send();
<script>
function sortResult(str)
{
if (str=="")
{
document.getElementById("result").innerHTML="";
return;
}
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("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","main-content-city.php?q="+str,true);
xmlhttp.send();
xmlhttp.open("GET","child-content-city.php?q="+str,true);
xmlhttp.send();
}
</script>
我的索引.php文件是这样的,并使用GET方法在主内容和子内容.html之间导航.html。
<?php
include('header.html');
include('main-content.html');
include('footer.html');
?>
我的主要内容和子内容是这样的:
<div id="result">
Content displayed here
</div>
获取以下所有代码,这些代码对于两个 ajax 调用都是相同的,并创建一个单独的函数 i.。e
function ajaxCall (){
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("result").innerHTML=xmlhttp.responseText;
}
}
}
然后,当您调用 ajaxCall 时,您只需添加相关的 SEND:
function whatEver(){
if (main-content.html is loaded)
{ ajaxCall();
xmlhttp.open("GET","main-content-city.php?q="+str,true);
xmlhttp.send();
}
else if (child-content is loaded)
{
ajaxCall();
xmlhttp.open("GET","child-content-city.php?q="+str,true);
xmlhttp.send();
}
}