【问题标题】:Refresh the dropdown options whenever a user click on the dropdown list每当用户单击下拉列表时刷新下拉选项
【发布时间】:2019-04-04 08:12:41
【问题描述】:

我用 html 和 php/mysql 创建了一个简单的下拉列表

<select name="location_id" id="location_id" class="form-control">
 <?php
   $sql = "SELECT * FROM locations";
   $result = mysqli_query($conn, $sql); 
   while($row=mysqli_fetch_assoc($result)){ ?>

      <option value="<?php echo $row['location_id'];?>">
       <?php echo $row['location_name'];?></option>             
 <?php } ?>
</select>



在从另一个页面插入新记录之前,它工作得很好。我需要刷新页面才能在下拉列表中获取新插入的记录。

在我当前的应用程序中,每当用户单击下拉列表时,我都需要刷新下拉选项而不刷新整个页面。选项应该从 mysql 数据库中实时获取。

我已经搜索过解决方案,但找不到类似的解决方案。

【问题讨论】:

    标签: php jquery html mysql ajax


    【解决方案1】:

    要仅刷新页面的一部分,您需要使用 JavaScript,具体来说是 AJAX。

    Ajax 让您无需重新加载整个页面即可发送 HTTP 请求和更新页面元素。

    你可以试试这样的

    <script>
    function refresh_items() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("location_id").innerHTML =
      this.responseText;
    }
    };
    xhttp.open("GET", "refresh_list.php", true);
    xhttp.send();
    }
    </script>
    
    <select name="location_id" id="location_id" class="form-control" onclick="refresh_items();">
    </select>
    

    现在您已经制作了客户端脚本,您希望 refresh_list.php 上的服务器端 PHP 看起来像这样

     <?php
       //all your SQL settings and stuff here
       $sql = "SELECT * FROM locations";
       $result = mysqli_query($conn, $sql); 
       while($row=mysqli_fetch_assoc($result)){ ?>
    
          <option value="<?php echo $row['location_id'];?>">
           <?php echo $row['location_name'];?></option>             
     <?php } ?>
    

    【讨论】:

    • 谢谢,它对我很有用,但是只需要在 javascript 中添加一个新行来初始化变量 var xhttp = new XMLHttpRequest();
    • 再次需要帮助,上面的代码在大多数浏览器上运行良好,但在 Safari 上不行,有什么可能的原因吗?
    • 在Safari中没有加载选项,我在控制台上检查过,没有发现错误。
    猜你喜欢
    • 1970-01-01
    • 2010-10-12
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    相关资源
    最近更新 更多