尝试使用jquery和ajax填充下拉列表

时间:2013-09-24 10:40:52

标签: javascript php jquery

这是我的代码: -

  <script>
           $(document).ready(function(){                               //#This script uses jquery and ajax it is used to set the values in
           $("#day").change(function(){             //# the time field whenever a day is selected.

           var day=$("#day").val();
           var doctor=$("#doctor").val();

           $.ajax({
                 type:"post",
                 url:"time.php",
                 data:"day="+day+"&doctor="+doctor,
                 dataType : 'json', 
                 success:function(data){
                            var option = '';
            $.each(data.d, function(index, value) {
                option += '<option>' + value.res + '</option>';
                });
            $('#timing').html(option);
                             }

                  });

                  });

                 });
   </script>

这是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);

    $i = 0;                                 //Initialize the variable which passes over the array key values

    $row = mysqli_fetch_assoc($result);    //Fetches an associative array of the row
    $index = array_keys($row);             // Fetches an array of keys for the row.

    while($row[$index[$i]] != NULL)
    {

        if($row[$index[$i]] == 1) {
            $res = $index[$i];              
            echo json_encode($res);

        }
        $i++;
    }       



  ?>

我希望在我的html页面上的select中插入时间值的选项看起来像这样: -

  <select id="timing" name="timing"></select>

我的java脚本代码正在将值发布到php脚本,但代码仍无效。我看到的javascript中没有任何错误。请帮助我

3 个答案:

答案 0 :(得分:2)

      var postUrl = "time.php";
      $.ajax({
            type: "POST",
            url: postUrl,
            data: {day: day,doctor: doctor},
            dataType: "json",
            success: function (data) {
                $.each(data, function (key, value) {
                    $('#timing').append('<option value="' + key + '">' + value + '</option>');
                });
            }
        });

答案 1 :(得分:0)

希望对你有所帮助

   success:function(data){
           var select= '<select>';
           var option = '';
            $.each(data.d, function(index, value) {
                option += '<option>' + value.res + '</option>';
            });
           select = select+option'</select>';
           $('#timing').html(select);
      }

HTML:

<div id="timing"> </div>

答案 2 :(得分:0)

    var day=$("#day option:selected").val();
    var doctor=$("#doctor option:selected").val();

    data:"{day:'"+day+"', doctor: '" + doctor + "'}" ,