繁体   English   中英

动态填充下拉列表,无需重新加载页面

[英]Dynamically populate dropdown list without reloading page

我有张桌子叫作course 其中包含字段

COURSEID, COURSENAME

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

STCODE, STNAME, COURSEID

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

我假设您的第一个下拉菜单具有课程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);

        }
    });
  });

H

您需要进行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这只是一个示例,根据您的需要和db进行更改。

<?
    $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>"

    }

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM