根据第一个下拉列表结果填充第二个下拉列表


Populate 2nd drop down based on first drop down result

我知道以前有人问过这个问题,但我似乎不知道如何在我的场景中应用。我在MySQL中得到了一个表,叫做subject,它由主题名称和主题级别组成。

例如:

Subject Name, Subject Level
 (Maths,P1)
 (English, P2)
 (Science,P1)
 (English,S3)

我的问题是,如果用户在第一个下拉列表中选择"主题级别",那么第二个下拉列表如何显示它所包含的主题名称?

例如,如果用户在第一个下拉列表中选择P1,它将只显示数学和科学。

提前感谢!

我现在将写下如何完成的过程,然后您将不得不为您不理解的部分找到教程。

因此:1步骤:从数据库中获取级别并生成级别下拉列表:

 <select id="level">
  <option value="p1">p2</option>
  <option value="p2">p2</option>
 </select>

2步骤:为受试者准备选择框:

<select id="subjects" style="display:none"> //this field should be hidden first
</select>

3步骤:使用jquery,为"级别"选择框添加监听器(这意味着每次用户选择任何级别(p1,p2…)时都会执行此功能:

<script>
  $('#level').on('change', function() {  //this chunk of code will be executed every time user reselects level value
    var selected = $(this).val(); //this is the value of selected level
    //here starts ajax method to communicate with server
    $.ajax({
    method: "POST",
    url: "getSubjectByLevel.php",
    data: { level: selected } //level is variable that will passed to getSubjectByLevel.php. You can get it in php file using $_POST["level"] and according this value generate sql query that will return only subject with this "level". Then you will have to generate array out of these subjects and return using normal "echo ArrayName" statement.
    })
    .done(function( subjects ) { //subjects is array of subjects returned from getSubjectByLevel.php
      var selectBoxHtml = '';
      for(i =0; i< subjects.length; i++){
        selectBoxHtml += '<option value='+subjects[i]+'>'+subjects[i]+'</option>';
      }
      $("#subjects").html(selectBoxHtml);  //put generated select box options in prepared earlier subjects select box
      $("#subjects").show(); //appear subjects select box which was hidden initially
     });
  });
</script>

这是一种实现你想要的东西的通用算法。如果您对无法理解的细节或概念问题有疑问,请随时提问。

使用ajax构建第二个下拉菜单的链式选择菜单示例。这种方法可以扩展到包括许多下拉列表,但这应该会让您对如何实现它有一个很好的想法。示例中没有涉及sql,只是一个模拟。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        /* 
        this might be a totally separate script in reality 
        but for demo purposes the ajax function will send the 
        requests to the same page that has the html form on.
        */
        /* 
            Here you would intercept the value being POSTed by the ajax function
            and construct then execute your sql. The response will then be sent back
            to the callback function.
        */
        $posted_value=$_POST['q'];
        for( $i=0; $i < 20; $i++ ) echo "<option value=$i>".$posted_value.'_'.$i;
        /* As it is the same page we want to stop here */
        exit();
    }
?>
<!doctype html>
<html>
    <head>
        <title>Chained Select Menu using ajax</title>
        <script>
            /* Very basic ajax function */
            function ajax(m,u,p,c){
                /*
                    m=method
                    u=url
                    p=params {name:value}
                    c=callback
                */
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call(this,xhr.response);
                };
                var params=[];
                for( var n in p )params.push(n+'='+p[n]);
                switch( m.toLowerCase() ){
                    case 'post':
                        p=params;
                    break;
                    case 'get':
                        u+='?'+params;
                        p=null;
                    break;  
                }
                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
                xhr.send( p );
            }
            /* Event listener - attached to select menu */
            function getdata(n){
                ajax.call( this, 'POST', document.location.href,{ q:n }, cbgetdata );
            }
            /* callback function that processes response data */
            function cbgetdata(r){
                document.getElementById('menu_2').innerHTML=r;
            }
        </script>
    </head>
    <body>
        <form name='geronimo'>
            <h1>Chained Dropdown menus</h1>
            <select name='menu_1' onchange='getdata( this.value )'>
                <option value='AL'>AL</option>
                <option value='AK'>AK</option>
                <option value='AZ'>AZ</option>
            </select>
            <select name='menu_2' id='menu_2'></select>
        </form>
    </body>
</html>