这是我的 JS 代码。然而,它只执行了最后一个ajax请求。是否有办法将它们放入 If 语句中,以便
如果(main-content.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>
我的index.php文件是这样的,并使用GET方法在main-content.html和child-content.html之间导航。
<?php
include('header.html');
include('main-content.html');
include('footer.html');
?>
我的主要内容和子内容是这样的:
<div id="result">
Content displayed here
</div>
最佳答案
采用以下所有代码,这些代码对于两个 ajax 调用都是相同的,并创建一个单独的函数,即......
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();
}
}
关于javascript - 如果满足条件则发送ajax GET请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28178799/