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

时间:2015-01-27 19:51:26

标签: 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>

1 个答案:

答案 0 :(得分:0)

获取以下所有代码,这些代码对于两个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();
 }
 }