Php 填充下拉列表

Php 填充下拉列表,php,ajax,Php,Ajax,我有三个下拉列表:国家、州和城市 我想根据国家/地区列表中的选择填充州列表,并根据州列表中的选择填充城市列表 下面是我如何尝试的 从国家列表中,使用onchage事件调用java脚本函数 <select name="country" id="id1" onchange="onCountryChange(this.value)"> 我使用以下代码获取状态值 <?php $countryname=$_GET["countryname"]; $connection = pg_co

我有三个下拉列表:国家、州和城市

我想根据国家/地区列表中的选择填充州列表,并根据州列表中的选择填充城市列表

下面是我如何尝试的

  • 从国家列表中,使用onchage事件调用java脚本函数

    <select name="country" id="id1" onchange="onCountryChange(this.value)">
    
  • 我使用以下代码获取状态值

    <?php
    $countryname=$_GET["countryname"];
    $connection = pg_connect("host=localhost port=5432 dbname=STAGE2 user=postgres password=jssate");
    if (!$connection){
        echo "<H1>Error in connection to Database</H1>";
        echo "<H2>Please try again</H2>.";
    }
    else{
        $query1="Select distinct(state) from master_table where country='$countryname'";
    $result = pg_query($connection,$query1);
    $numrows = pg_numrows($result);     
    if ($numrows>0){
    echo "State <select name="state" id="stateid">;
    for ($row_index=0;$row_index<$numrows;$row_index++)
    {
        $state_name=pg_result($result,$row_index,0);
        echo "<option value="$state_name\">$state_name</option>";
            }
    echo "</select>";
    }
    
    }
    pg_close($connection);
    ?>
    

    在html页面中创建3个选择国家、城市和州选项

    • 只有国家/地区选择元素才有选项,州和城市将为空
    • 在更改country send和ajax请求获取状态的事件时,作为响应,只发送选项元素不要像您所做的那样将它们包装在SELECT中
    • 将这些选项推送到州的select元素中

      document.getElementById('state').innerHTML(state\u ajax\u response)

    然后在html文件中创建函数,该函数将在状态选择更改时调用,并再次对城市选择重复该过程

    希望你得到它


    只需发送选项元素作为响应。

    您能把代码布置得更好一点吗?因为我试过几次编辑,所以很难阅读。有些东西不可靠。Javascript中的转义字符是必要的吗?为什么不试试xmlhttp=newActiveXObject(“Microsoft.xmlhttp”);
    <?php
    $countryname=$_GET["countryname"];
    $connection = pg_connect("host=localhost port=5432 dbname=STAGE2 user=postgres password=jssate");
    if (!$connection){
        echo "<H1>Error in connection to Database</H1>";
        echo "<H2>Please try again</H2>.";
    }
    else{
        $query1="Select distinct(state) from master_table where country='$countryname'";
    $result = pg_query($connection,$query1);
    $numrows = pg_numrows($result);     
    if ($numrows>0){
    echo "State <select name="state" id="stateid">;
    for ($row_index=0;$row_index<$numrows;$row_index++)
    {
        $state_name=pg_result($result,$row_index,0);
        echo "<option value="$state_name\">$state_name</option>";
            }
    echo "</select>";
    }
    
    }
    pg_close($connection);
    ?>
    
        <div id="statenames">
        //Original select list placed here is replaced by the one returned by server.
        </div>