繁体   English   中英

这是如何基于从URL获得值来处理两个Ajax请求?

[英]Is this how to handle two ajax request based on get value from url?

我想根据所选城市对数据进行排序。 主页和产品页面上的数据不同。 因此,如果我查看主页并选择城市,则将发送第一个ajax请求;如果我查看产品页面并选择城市,则将发送第二个ajax请求。

因此,下面的ajax代码将基于if条件以及if语句中的条件告诉浏览器URL中的GET变量正在查看哪个页面,从而发送请求。 我不知道以下if语句的语法是否正确? 如果没有,实现我的目标的正确方法是什么?

示例网址: http://localhost/myproject/index.php?view = home-page

<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) {
                if ($_GET["view"] == "home-page") {
                    document.getElementById("result").innerHTML = xmlhttp.responseText;
                    xmlhttp.open("GET", "home-page-new.php?q=" + str, true);
                    xmlhttp.send();
                }
                if ($_GET["view"] == "product-page") {
                    document.getElementById("result").innerHTML = xmlhttp.responseText;
                    xmlhttp.open("GET", "product-page-new.php?q=" + str, true);
                    xmlhttp.send();
                }
            }
        }
    }
</script>

这是HTML:

<select name="sortby" class="form-control" id="city"  onchange="sortResult(this.value)">
    <option value="">Choose CiTY</option>
    <option value="City 1">City 1</option>
    <option value="City 2">City 2</option>
    <option value="City 3">City 3</option>
</select>

这是主页html:

<div id="result">
  Old content will be replaced by new content here
</div>

这是产品页面html:

<div id="result">
  Old content will be replaced by new content here
</div>

首先,您不能直接在JavaScript中使用$ _GET [“ view”]。 像下面这样取一个变量:

   <script >
    var view = <?php echo $_GET["view"]; ?>;
    ...........
if(view =="home-page")
 {
   document.getElementById("result").innerHTML=xmlhttp.responseText;
   xmlhttp.open("GET","home-page-new.php?q="+str,true);
   xmlhttp.send();
 }
 if(view =="product-page")
 {
   document.getElementById("result").innerHTML=xmlhttp.responseText;
   xmlhttp.open("GET","product-page-new.php?q="+str,true);
   xmlhttp.send();
 }
 ................
  </script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM