【发布时间】:2016-07-04 20:19:51
【问题描述】:
我正在使用 PHP 编写服务器端并卡住了。
我想使用表单的选择标签创建一组输入字段。 选择的选项应该从我的数据库中获取,并且在第一个输入中选择的选项将决定第二个输入中的选项。
例如,这两个字段是国家和州。首先,用户选择他们的国家名称,这将决定出现在州输入字段中的州列表。当用户更改国家/地区时,我希望列表动态更改。
【问题讨论】:
我正在使用 PHP 编写服务器端并卡住了。
我想使用表单的选择标签创建一组输入字段。 选择的选项应该从我的数据库中获取,并且在第一个输入中选择的选项将决定第二个输入中的选项。
例如,这两个字段是国家和州。首先,用户选择他们的国家名称,这将决定出现在州输入字段中的州列表。当用户更改国家/地区时,我希望列表动态更改。
【问题讨论】:
您可以在 PHP 中执行此操作,每次提交一个选择。
例如:
<form action="selectState.php" method="post">
<select name="country">
<option value="countryName">countryName</option>
...
</select>
</form>
然后您在 selectState.php 中获得 $_POST['country'] 的值并以您想要的方式打印选择:
<form action="" method="post">
<select name="state">
<?php
// select use $_POST['country'] to customize the select option's
?>
</select>
</form>
使用 AJAX 是一种更加用户友好的解决方案(不需要新页面或刷新)。
所以你可以使用这种形式:
<form action="selectState.php" method="post">
<select name="country" onchange="ajaxFunction(this.value)">
<option value="countryName">countryName</option>
...
</select>
<select name="state" id="stateList">
<!-- here we'll put the states we want -->
</select>
</form>
每次用户更改选择值时都会调用 ajaxFunction() 并将当前选择的值传递给函数。
这里是 ajaxFunction(注意:这个例子使用 jQuery,但你可以用 vanilla javascript 来做):
function ajaxFunction(val){
$.ajax({
type: 'post', // choose the method
url: 'page.php', // choose the 'action' page
data: {
country:val // send the data
},
success: function (response) {
// this tell the browser what to do with the response of 'page.php'
// in this case we are telling to put everything we get to the HTML element with stateList id
document.getElementById("stateList").innerHTML=response;
}
});
}
你需要它的“page.php”来查询数据库的最后一件事(注意:这是伪代码):
<?php
// Query the DB for the states with country = $_POST['country']
while(results){
echo '<option value="results[$i]">results[$i]</option>';
}
?>
【讨论】:
您是否使用了 php 框架,例如 Laravel(推荐)或 Codeigniter(不确定是否仍在开发中)。
如果是这样,您可以构建一个二维 php 国家/地区数组,每个国家/地区都有一个国家的子数组。
这可以直接放入渲染页面(视图)。 使用类似的东西
var countries_list =<?php echo json_encode($countries_array); ?>;
将直接将其注入一个 javascript 数组中,当国家/地区选择发生变化时,您可以使用该数组填充州选择。
或者使用 ajax,但这会更慢并且更多地访问服务器。
【讨论】: