简体   繁体   English

两个选择框与ajax

[英]two select box with ajax

I need your help with ajax select box please. 我需要ajax选择框的帮助。

I have 2 selectboxs: 我有2个选择框:

  1. area 区域

  2. cities 城市

when I choose area the option in the CITIES selectbox change accourding the area I chose. 当我选择区域时,“城市”选择框中的选项会根据我选择的区域进行更改。

It's work OK, But when I load the page (for ie: edit the data) I don't see the right city (the selectbox pointer stand on the first city in the list accourding the DB area that I chose before). 一切正常,但是当我加载页面时(例如,编辑数据),我看不到正确的城市(selectbox指针位于列表中第一个城市上,这与之前选择的DB区域相符)。

What do I need to change? 我需要更改什么?

Thanks 谢谢

Client Site: 客户网站:

<p><label>Area</label> 
    <select name='areaID' id='areaID'>
        <?PHP
        $query = mysql_query("SELECT * FROM `areas` ORDER BY id ASC "); 
        while($index = mysql_fetch_array($query)) 
        {
            $db_area_id = $index['id'];
            $db_area_name = $index['name'];
            if ($db_area_id == $userDetails['areaID'])
                echo "<option value='$db_area_id' selected>$db_area_name</option>";         
            else    
                echo "<option value='$db_area_id'>$db_area_name</option>";
        }
        ?>
    </select><span>*</span>
</p>

<p><label>City</label>
    <select id='cityID' name='cityID'>  </select>
</p>


<script>
$(function () {
    function updateCitySelectBox() {
        var areaID = $('#areaID').val();
        $('#cityID').load('ajax/getCities.php?areaID=' + areaID);

        return false;
    }

    updateCitySelectBox();
    $('#areaID').change(updateCitySelectBox);
});
</script>

Server Side: 服务器端:

$areaID = (int) $_GET['areaID'];

$second_option = "";

$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = $areaID ORDER BY id ASC");
while($index = mysql_fetch_array($query2)) 
{
    $id = $index['id'];
    $name  = $index['name'];
    $second_option .= "<option value='$id'>$name</option>";

}
echo $second_option;

Try to add following line of code. 尝试添加以下代码行。 you need to call the function at the time of window load. 您需要在加载窗口时调用该函数。

$(document).ready(function(){
    window.load = updateCitySelectBox();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM