javascript - 如果满足条件则发送ajax GET请求

标签 javascript php jquery mysql ajax

这是我的 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/

相关文章:

javascript - 如何在其他可观察对象完成时返回可观察对象

javascript - Jquery:基于2个按钮的点击功能隐藏和显示div

jquery - 检查 div 是否存在于跨度 jQuery 之外

javascript - 在对象数组中查找索引

javascript - Konvajs 如何动态更改图像 src

php - 跟踪用户之间的付款?

php - 将 mysql 查询的结果插入现有表

javascript - html转json获取div数据

javascript - xmlHttpRequest 卡在就绪状态 1

php - 如何创建一个执行回调的 Twig 自定义标签?