从数据库中动态填充<select> </select>

时间:2012-03-21 04:40:13

标签: php javascript mysql ajax

我正在尝试使用AJAX填充选择列表,如下所示:

HTML:

<table>
<tr>
    <td>Select State</td>
    <td>
    <select name="tractDrop" onchange="populateSelect(this.value)">
       <option value = "TX">TX</option>
       <option value = "LA">LA</option>
       <option value = "CA">CA</option>
    </select>
    </td>
   </tr>
   <tr>
    <td>
        Select County
    </td>
    <td>
        <select name="selectCounty">
        </select>
    </td>
   </tr>
</table>

JAVASCRIPT:

function populateSelect(str)
{
    if (str=="")
        {
            document.getElementById("selectCounty").innerHTML="";
            return;
         }
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("selectCounty").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","selectajax.php?q="+str,true);
    xmlhttp.send();
}

PHP:

<?php
    $q=$_GET["q"];
    include '../include/engine.php';
    $sql="SELECT DISTINCT * FROM tractIndex WHERE tractState = '".$q."'";
    $result = mysql_query($sql);
    echo ("<option value=''> Select County </option>");
    while($row = mysql_fetch_assoc($result))
    {
        echo ("<option value = $row[tractCounty]>$row[tractCounty]</option>");
    }
?>

数据库表tractIndex包含以下列:IDtractStatetractCounty

除了我试图填充选择选项的javascript中的部分外,一切正常:

document.getElementById("selectCounty").innerHTML=xmlhttp.responseText;

感谢任何愿意提供帮助的人。抱歉这么傻!

3 个答案:

答案 0 :(得分:2)

如果您发布的代码是正确的,则错误很明显,

document.getElementById("selectCounty").innerHTML=xmlhttp.responseText;
//The line above will try to find an element with the id 'selectCountry'

据我所知,你的元素都没有这样的身份。试试这个改变

<select id="selectCounty"></select>
//Note the change from "name" to "id"

答案 1 :(得分:1)

你没有给下拉列表提供id。你应该先给id。 其次,我不认为写作

document.getElementById("selectCounty").innerHTML=xmlhttp.responseText;

您可以在选择框中添加选项元素。你需要提出其他解决方案。

答案 2 :(得分:0)

PHP:

 echo "<select name='country'>";
    echo "<option value=''> Select County </option>";

        while($row = mysql_fetch_assoc($result))
        {
            echo ("<option value = $row[tractCounty]>$row[tractCounty]</option>");
        }

    echo "</select>";

HTML: 替换

        <select name="selectCounty">
        </select>

<div id="city">
 </div>

希望这会有所帮助

相关问题