从db中拉出的级联下拉框

时间:2012-04-11 21:03:20

标签: php html ajax

我正在尝试使用php和ajax从db填充两个下拉框。第一个下拉框只有一个选项,但是当你选择它时,它应该填充第二个下拉框,其中我的学校的不同部门被从数据库中拉出。在选择部门时,该部门的所有课程都应显示在第三个下拉框中。现在我只想尝试填充所有部门的下拉框,当你点击它时它不会填充任何东西。我认为在下拉框中编写部门名称的循环存在问题。这是我的代码

的index.php

<html>
    <head>
        <meta http-equiv="Content-Type" 
            content="text/html; charset=iso-8859-1">
        <script language="javascript" type="text/javascript">

            function getXMLHTTP() { //function to return the xml http object
                var xmlhttp=false;    
                try{
                    xmlhttp=new XMLHttpRequest();
                }
                catch(e)    {        
                    try{            
                        xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch(e){
                        try{
                            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                        }
                        catch(e1){
                            xmlhttp=false;
                        }
                    }
                }

                return xmlhttp;
            }

            function getDept() {        

                var strURL="findDept.php";
                var req = getXMLHTTP();

                if (req) {

                    req.onreadystatechange = function() {
                        if (req.readyState == 4) {
                            // only if "OK"
                            if (req.status == 200) {                        
                                document.
                                    getElementById("deptdiv").
                                        innerHTML=req.responseText;
                            } else {
                                alert("There was a problem " +
                                    "while using XMLHTTP:\n" + req.statusText);
                            }
                        }                
                    }            
                    req.open("GET", strURL, true);
                    req.send(null);
                }        
            }
            function getCourse(deptId) {        
            var strURL="findCourse.php?dept="+deptId;
            var req = getXMLHTTP();

            if (req) {
                req.onreadystatechange = function() {
                        if (req.readyState == 4) {
                            // only if "OK"
                            if (req.status == 200) {                        
                                document.
                                    getElementById('coursediv').
                                        innerHTML=req.responseText;
                            } else {
                                alert("There was a problem " +
                                    "while using XMLHTTP:\n" + req.statusText);
                            }
                        }                
                    }            
                    req.open("GET", strURL, true);
                    req.send(null);
                }
            } 
        </script>
    </head>
    <body bgcolor= 'red' >
        <p>
            <font size="8" face="arial" 
                color="black">WELCOME TO SCHEDULE BUILDER</font>
        </p>
        <form method="post" action="" name="form1">
            <table width="60%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                    <td width = "150">Semester</td>
                    <td width="150">
                        <select name="semester onChange="getDept()">
                            <option value="">Select Semester</option>
                            <option value ="1">Spring 2012</option>
                        </select>
                    </td>
                </tr>
                <tr style="">
                    <td>Department</td>
                    <td >
                        <div id="deptdiv">
                            <select name="department">
                                <option>Select Department</option>
                            </select>
                        </div>
                    </td>
                </tr>
                <tr style="">
                    <td>Course</td>
                    <td >
                        <div id="coursediv">
                            <select name="course">
                                <option>Select Department First</option>
                            </select>
                        </div>
                    </td>
                </tr>
                <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                </tr>
                <tr>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                </tr>
            </table>
        </form>
    </body>
</html>

findDept.php

<?
    $link = mysql_connect("sql2.njit.edu", "sk442_proj", "jZ1MOA0X");
    if (!link) {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("sk442_proj");
    $query="SELECT abbrev FROM department";
    $result=mysql_query($query);
?>
<select name="department" onchange="getCourse(this.value)">
    <option>Select Department</option>
<? while($row=mysql_fetch_array($result)) { ?>
    <option value=$row['abbrev']><?=$row['abbrev']?></option>
<? } ?>
</select>

2 个答案:

答案 0 :(得分:0)

这是一个动态下拉,我用它可能会有所帮助:

main.php

include('pla2.php');
<script>
$(document).ready(function() {
    $('#wait_1').hide();
    $('#drop_1').change(function(){
      $('#wait_1').show();
      $('#result_1').hide();
      $.get("pla2.php", {
        func: "drop_1",
        drop_var: $('#drop_1').val()
      }, function(response){
        $('#result_1').fadeOut();
        setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
      });
        return false;
    });
});


function finishAjax(id, response) {
  $('#wait_1').hide();
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn();
} 
</script>
<select name="drop_1" id="drop_1">

      <option value="" selected="selected" disabled="disabled">Select a Category</option>

      <?php getTierOne(); ?>

    </select> 

    <span id="wait_1" style="display: none;">
    <img alt="Please Wait" src="ajax-loader.gif"/>
    </span>
    <span id="result_1" style="display: none;"></span> 
    <span id="wait_2" style="display: none;">
    <img alt="Please Wait" src="ajax-loader.gif"/>
    </span>
    <span id="result_2" style="display: none;"></span> 

pla2.php

function getTierOne()
{
    $catresult = mysql_query("SELECT DISTINCT category FROM categories") 
    or die(mysql_error());

      while($tier = mysql_fetch_array( $catresult )) 

        {
           echo '<option value="'.$tier['category'].'">'.$tier['category'].'</option>';
        }

}

//**************************************
//     First selection results     //
//**************************************
if($_GET['func'] == "drop_1" && isset($_GET['func'])) { 
   drop_1($_GET['drop_var']); 
}

function drop_1($drop_var)
{  
    include_once('db.php');
    $result = mysql_query("SELECT DISTINCT level1 FROM categories WHERE category='$drop_var'") 
    or die(mysql_error());

    echo '<select name="drop_2" id="drop_2">
          <option value=" " disabled="disabled" selected="selected">Choose one</option>';

           while($drop_2 = mysql_fetch_array( $result )) 
            {
              echo '<option value="'.$drop_2['level1'].'">'.$drop_2['level1'].'</option>';
            }

    echo '</select>';

答案 1 :(得分:0)

这是我如何使用我的动态选择菜单,我更新第二个菜单所在的分区,分类是第一个菜单,然后品牌第二个

    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            var ajaxDisplay = document.getElementById('brand');
            ajaxDisplay.innerHTML = ajaxRequest.responseText;
        }
    }
    var category = document.getElementById('category').value;
    var queryString = "&category=" + category;
    ajaxRequest.open("GET", "cat_to_brand_special.php?section=cat" + queryString, true);
    var ajaxDisplay = document.getElementById("brand");
    ajaxDisplay.innerHTML = "<p style=\"padding-left:8px; font-size:11px; color:#DD0000\"><img style=\"border: 0px solid\" src='ajax-loader-form.gif'/> Loading...</p>"
    ajaxRequest.send(null);

html部分......

   <table><td>
       <div>
          <select id="category" name="category" onchange='ajaxFunction("special_cat")'>  <option value="000">--- Select Category ---</option><?php echo $menu_list?></select>
       </div>
   </td>
   <td>
       <div id="brand">
           <select id='brands' name="brands"><option value="000">--- Select Brand ---</option><?php echo $menu_list_2; ?></select>
       </div>
   </td><table>

将会输出的PHP部分

    $cat=$_GET['category'];
    $display="<select name=\"brand\">";
    $result=mysql_query("select name from brands where category = '$cat'")
    while($db_fields=mysql_fetch_assoc($result){
        $name=$db_fields['name'];
        $display .= "<option>$name</option>";
    }
    $display .="</select>";
    echo $display;

只是一个你可以使用的例子......