Заполнение выпадающего списка с помощью jquery

0

Я пытаюсь заполнить выпадающий список, используя jquery и ajax.

Вот как выглядит мой код.

<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,
                          success:function(data){
                             $("#time").html(data);
                             }
                      });

                });
           });
   </script>

Здесь time.php

   //some code for connecting to database

 $doctor = $_POST['doctor'];

 $day = $_POST['day'];

$query="SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";

$result = mysqli_query($con, $query);

echo" 
<select name='timing' id='timing'>";
$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 jason_encode($res);

            echo "<option value='"  . $index[$i]."'>" . $index[$i] . "</option>";
    }
    $i++;
    }       

    echo "</select>";

  ?>

Это просто помещает список на time.php в div раз на моей странице. Есть ли способ, чтобы я мог отображать отдельные параметры из списка во времени.php и добавлять их в раскрывающийся список на моей странице?

Заранее спасибо.

Теги:

3 ответа

2

пытаться:

success:function(data)
{
var option = '';
$.each(data.d, function(index, value) {
    option += '<option>' + value.YourReturnParam + '</option>';
    });
 $('#yourDdlID').html(option);
}
  • 0
    Хорошо. Я, что бы YourReturnParam был здесь? также нужно что-то вроде option + = "<option value = 'value.YourReturnParam.>" + value.YourReturnParam + "</ option>", поэтому я могу отправить его через форму
  • 0
    YourReturnParam означает то, что json дает вам связать.
Показать ещё 7 комментариев
0
<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,
                      success:function(data){
                        var jdata=eval('('+data+')');;
                        var str='';
                        for(var i=0;i<jdata.length;i++)
                        {
                            str.='<option>'+jdata[i]+'</option>';
                        }
                         $("#time").html(str);
                         }
                  });

            });
       });

time.php вернется как

$ res = array ('a', 'b', 'v') echo json_encode ($ res);

  • 0
    Привет, не могли бы вы сказать мне, что такое а, б, в?
0

Было бы проще, если переменная данных, используемая в обратном вызове успеха, - это JSON или массив.

success:function(data)
{
    var option = $('#time');

    //Remove old options
    option.empty(); 

    //It makes it easier if you create an array to store all of the values that you want to
   //populate the select tag with. I'm not sure if the data that returned is in the form of an array or not
   var newOptions = {'key1': 'value1','key2': 'value2', 'key3': 'value3'};  

   //Loop thru and change each option tag
   $.each(newOptions, function(key, value) {
       option.append($('<option></option>').attr('value', value).text(key));
   });
}

И html может выглядеть примерно так, я предполагаю?

<select id="time">
    <option value="val">Text</option>
    <option value="val">More Text</option>
</select>

Ещё вопросы

Сообщество Overcoder
Наверх
Меню