这是如何处理基于从 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>