我正在尝试开发一个JS函数,该函数根据之前下拉列表中的选择创建一个新的下拉列表。基本上是一个下拉菜单,根据州的选择选择城市列表。有人有什么建议吗?
这是我正在使用的javascript:
function city() {
var opt = document.getElementById('State');
var sel = opt.options[opt.selectedIndex].value;
var dropdown = document.getElementById('City');
document.write("<?php mysqli_select_db($GLOBALS['SSDN'],$database_SSDN); $query_City = 'SELECT * FROM city WHERE State = sel ORDER BY City ASC'; $City = mysqli_query($GLOBALS['SSDN'],$query_City) or die(mysql_error()); while ($row_City = mysqli_fetch_array($City, MYSQL_ASSOC)) ?>");
var o = document.createElement('option');
o.text = document.write("<?php echo $row_City['City'];?>");
o.value = document.write("<?php echo $row_City['City'];?>");
dropdown.options.add(o);
}
这是html:
<td><select name="State" class="Field" id="State">
<?php
while ($row_Recordset1 = mysqli_fetch_array($Recordset1, MYSQL_ASSOC)) {
?>
<option value = "<?php echo $row_Recordset1['State'];?>"><?php echo $row_Recordset1['State'];?></option>
<?php
}
?>
</select></td>
</tr>
<tr height="50">
<td><div align="right" class="Label">Select New Rehbar City :</div></td>
<td> </td>
<td><select name="City" class="Field" id="City" onfocus="City();">
</select></td>
</tr>
答案 0 :(得分:0)
我记得2011年的这个:http://tutorialzine.com/2011/11/chained-ajax-selects-jquery/
它被称为链式选择框。上面的链接提供了有关如何实现它的教程。看看它也许它会帮助你。
答案 1 :(得分:0)
Javascript是一种客户端脚本(编程)语言,PHP是一种服务器端编程语言,这意味着当页面已经刷新到客户端浏览器中时,您无法运行PHP代码,并且只能在页面运行时运行Javascript代码已经加载了!
这些行没有意义,也不会给你想要的结果:
document.write("<?php mysqli_select_db($GLOBALS['SSDN'],$database_SSDN); $query_City = 'SELECT * FROM city WHERE State = sel ORDER BY City ASC'; $City = mysqli_query($GLOBALS['SSDN'],$query_City) or die(mysql_error()); while ($row_City = mysqli_fetch_array($City, MYSQL_ASSOC)) ?>");
o.text = document.write("<?php echo $row_City['City'];?>");
o.value = document.write("<?php echo $row_City['City'];?>");
将您的选项(数据)放在javascript变量中,然后在脚本中使用它们,如下所示:
<script>
var myOptions = [
<?php
// Select and fetch the data from database
// Loop over your selected data and flush them into your javascript array
while ($row_City = mysqli_fetch_array($City, MYSQL_ASSOC)){
// if still have data:
?>'<?php echo $row_City["field_name"] ?>',<?php
// else:
?>'<?php echo $row_City["field_name"] ?>'<?php
}
?>
];
for (option in myOptions){
// add each option to your drop down element
}
</script>