动态填充下拉列表而不重新加载页面

时间:2015-04-16 11:43:39

标签: php mysqli

我有一张名为course的表格。 其中包含字段

COURSEID, COURSENAME

另一个名为STUDENTS的表。其中包含

STCODE, STNAME, COURSEID

我已预先下载了课程下拉列表。我想从第一个下拉列表中选择course中的学生填充第二个下拉列表,而不重新加载页面。

2 个答案:

答案 0 :(得分:3)

我假设您的第一个下拉列表具有课程ID的值,除非并且直到这变得复杂:

$('select[name=\'course\']').on('change', function() {
    //fetch the course_id of the selected course
    course_id = $('select[name=\'course_id\']').val();

    $.ajax({
      //here sending your data to the file where the function will get your course_id and select students for it and then return it
      url: 'path_to_some_file.php' +  course_id,
      dataType : 'json',
      success: function(json) {
          //this is the success of the ajax. I have returned it in json format but you don't need to. send it in simple array but don't forget to return from the ajax function you called. Below lines is doing nothing but populating your student dropdown and then appending it to the dropdown.

          html = '<option value=""> --- Please Select --- </option>';
          for (i = 0; i < json.length; i++) {
                html += '<option value="' + json[i]['student_id'] + '"';
                html += '>' + json[i]['student_name'] + '</option>';
          }
          $('select[name=\'name_of_your_second_dropdown\']').html(html);

        }
    });
  });

ħ

答案 1 :(得分:2)

您需要进行ajax调用才能在更改第一个选择框时执行此任务。下面是脚本。 您可能需要包含jquery库。

  $(document).ready(function()
{

    $('.select').change(function()  // function will work when option will change in select
    {

        var course_id = $('.select').val();
        $.ajax({
        type:"post", 
      url: 'getdetail.php' ,     // url to the php file to get the response 
      data:'course_id='+  course_id,
      success: function(msg) {
          $('.select2').html(msg);

        }
        });
    })
})

html看起来像这样

<select class="select">
        <option value="1">Course1</option>
        <option value="2">Course1</option>
        <option value="3">Course1</option>  
    </select>

    <select class="select2">
        <option>select1</option>

    </select>

你的php文件将从db获取数据。这看起来应该是这样的。 getdetail.php这只是根据您的需要和数据库进行更改的示例。

<?
    $course_id=$_REQUEST['course_id'];     // selected course id here 
    $sql_query="query here " ; // make an sql query to fetch the students from the course.  
    while($result)
    {
        echo "<option value='".$val."'>".$name."</option>"

    }

?>
相关问题