【发布时间】:2014-05-09 14:30:23
【问题描述】:
我目前正在实现一个包含 AJAX 请求的三重依赖下拉菜单(想想国家->州->城市)。
这里是我的下拉结构的代码sn-p:
//create a drop down of available accounts
echo 'Available Accounts: ';
echo '<select name="dropAccounts" class="dropAccounts">';
//if there is at least one account available
if (count($accsAvailable) > 0) {
echo '<option value="0">---Select an account---</option>'; //default option
foreach ($accsAvailable as $account) {
//populate from API
echo '<option value=' . $account->getId(). '>' . $account->getName() . '</option>';
}
} else {
echo '<option value="0">---No accounts available---</option>'; //else if no accounts exist
}
echo '</select>';
//for available webproperties
echo '<br> Available Webproperties: ';
echo '<select name="dropProperties" class="dropProperties">';
echo '<option selected="selected">---Select a webproperty---</option>';
echo '</select>';
//for available profiles
echo '<br> Available Profiles: ';
echo '<select name="dropProfiles" class="dropProfiles">';
echo '<option selected="selected">---Select a profile---</option>';
echo '</select>';
重要的变量是dropAccounts(国家)、dropProperties(州)和dropProfiles(城市)。第一个下拉列表由 API 调用填充,然后 AJAX 请求在 onchange 事件中从其中获取值:
<script type="text/javascript">
$(document).ready(function()
{
$(".dropAccounts").change(function()
{
var accountID = $(this).val(); //gets the account ID from drop-down value
$.ajax
({
type: "POST",
url: "propertyID.php",
data: {
'accountID' : accountID
},
cache: false,
success: function(html)
{
$(".dropProperties").html(html);
}
});
});
});
</script>
然后 propertyID.php 然后像这样填充dropProperties(假设我正在从数据库中获取值):
if($_POST['accountID'])
{
if ($accountID != "0") {
foreach ($webItem as $item) {
echo '<option value=' . $item->getId() . '>' . $item->getName() . '</option>';
}
}
}
else {
echo '<option value="0">---Select a webproperty---</option>';
}
我同样设置了第三个下拉菜单 (dropProfiles) 以完全相同的方式填充,假设当第二个下拉菜单重新填充时它会触发 javascript onchange 事件。但是,当我让第二个下拉列表重新填充时,它不会执行第三个下拉列表的 javascript。
这是应该触发 PHP 脚本填充 dropProfiles 的 javascript onchange 函数:
<script type="text/javascript">
$(document).ready(function()
{
$(".dropProperties").change(function()
{
var id = $(this).val(); //gets the profile ID from drop-down value
$.ajax
({
type: "POST",
url: "profileID.php",
data: {
'id' : id
},
cache: false,
success: function(html)
{
$(".dropProfiles").html(html);
}
});
});
});
</script>
有解决办法吗?我是不是走错了路?
【问题讨论】:
标签: javascript php jquery ajax onchange