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

时间:2015-12-27 09:39:41

标签: javascript php

我知道之前已经问过这个问题,但是,我似乎不知道如何在我的场景中应用。我在MySQL中找到了一个名为subject的表格,其中包含主题名称和主题级别。

例如:

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

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

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

提前致谢!

2 个答案:

答案 0 :(得分:0)

使用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>

答案 1 :(得分:0)

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

所以: 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,为“level”选择框添加监听器(这意味着每次用户选择任何级别(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>

这是实现您想要的一般算法。如果您对细节或概念问题有疑问,请不要随意询问。