PHP 用 jquery 填充下拉框

PHP populate drop box with jquery

本文关键字:填充 jquery PHP      更新时间:2023-09-26

我有一个脚本,它从脚本php中获取选项以填充主页上的下拉列表。

这是 JavaScript

   <script>
   //# this script uses jquery and ajax it is used to set the values in
           $(document).ready(function(){   
                //# the time field whenever a day is selected. 
                $("#day").change(function() {   
                      var day=$("#day").val();
                      var doctor=$("#doctor").val();
                      $.ajax({
                          type:"post",
                          url:"time.php",
                          data:"day="+day+"&doctor="+doctor,
                          dataType : 'json'
                          success: function(data) {
                                //# $("#time").html(data);
                                var option = '';
                                $.each(data.d, function(index, value) {
                                     option += '<option>' + value.timing + '</option>';
                                });
                                $('#timing').html(option);
                             }
                       });
                  });
             });
   </script>

这是从数据库中获取数据的 php 脚本。

  <?php
    $con = mysqli_connect("localhost","clinic","myclinic","myclinic");
    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $doctor = $_POST['doctor'];
    $day = $_POST['day'];
    $query = "SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
    $result = mysqli_query($con, $query);
    //$res = array();
    echo "<select name='timing' id='timing'>";
    //Initialize the variable which passes over the array key values
    $i = 0;                                 
    //Fetches an associative array of the row
    $row = mysqli_fetch_assoc($result);
    // Fetches an array of keys for the row.    
    $index = array_keys($row);             
    while($row[$index[$i]] != NULL)
    {
        if($row[$index[$i]] == 1) {             
            //array_push($res, $index[$i]);
            json_encode($index[$i]);
            echo "<option value='"  . $index[$i]."'>" . $index[$i] . "</option>";
        }
        $i++;
    }       
    echo json_encode($res);
    echo "</select>";
  ?>

它不起作用。我从控制台收到一个错误,说在线 javasrcipt 中缺少"}"

  $("#day").change(function(){

我似乎也找不到错误。

您需要

在触发错误的行上方的行上添加一个逗号:

dataType : 'json',

这是因为您上面的行上没有逗号...

很难说问题在哪里,因为你把事情混在一起了。在Javascript方面,你期望JSON,但在PHP方面,你生成HTML。

使用 JSON 在服务器和浏览器之间发送数据。确保实际生成有效的 JSON 且仅生成 JSON。

此行不执行任何操作(函数返回值,但不修改它)

json_encode($index[$i]);

这一行没有意义 - 变量 $res 未初始化;

echo json_encode($res);