我的目标是有一个包含美国各州的下拉菜单,在选择一个州后,第二个下拉菜单将填充该州的城市。由于我不想将所有城市存储在我的数据库中,我有一个名为 list-of-cities.php 的 PHP 文件,它将存储来自所有州的城市数组。
以下代码是使 XMLHTTPREQUEST 对象从 list-of-cities.php 以及下拉表单请求信息的 JS 和 HTML。函数 AddToOptionsList() 将从 XMLHTTPREQUEST 对象的 responseText(它是 list-of-cities.php 中的数组中的一个城市)接收到的值添加到“cities”下拉菜单中。
function PopulateCities() {
var statesList = document.frmMain.states;
var stateValue = statesList[statesList.selectedIndex].value;
var i = 0;
do {
//create new XMLHTTPRequest object
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 )
{
var responseText = xmlhttp.responseText;
if( responseText == null){
//the request sent a null value from the cities array therefore we reached the end of it
break;
} else{
//Add the value received from the response to the "cities" option list
AddToOptionList(document.frmMain.cities, i, responseText);
}
}
}
xmlhttp.open("GET","http://localhost//wp-content/themes/list-of-cities.php?q="i+stateValue,false);
xmlhttp.send();
i++;
}
while(true);
}
function AddToOptionList(OptionList, OptionValue, OptionText) {
// Add option to the bottom of the list
OptionList[OptionList.length] = new Option(OptionText, OptionValue);
}
<form name="frmMain">
<div id="choose_state">
Select a state from the drop down menu:<select name="states" onChange="PopulateCities();">
<option value="choose_state" selected="selected">Choose a state</option>
<option value="florida">Florida</option>
<option value="newyork">New York</option>
<option value="california">Callifornia</option>
<option value="northcarolina">North Carolina</option>
</select>
</div><!--choose_state -->
<select name="cities" >
<option> Choose a city</option>
</select>
</form>
以下是 list-of-cities.php 代码,目前只有佛罗里达州的城市数组用于测试目的。从 XMLHTTPREQUEST 对象传递的 $q 参数的格式为“i + 州名”,以便跟踪城市数组中的位置。
<?php
$florida[]="Gainesville";
$florida[]="Miami";
$florida[]="Tampa";
$florida[]="Orlando";
$florida[]="Jacksonville";
$florida[]="Melbourne";
$florida[]="Tallahassee";
//$newyork[] = "Manhattan";
//$newyork[] = "Brooklynn";
//$newyork[] = "Queens";
//get the q parameter from URL (i + State name)
$q=$_GET["q"];
$i = substr($q,0,1); //first char of $q contains the position in the city array
$state = substr($q, 1, strlen($q)-1); //gives the state name from $q
if( $state == "florida" ) {
echo $florida[$i];
}
当前,所有这些代码一起用于使用 $florida[] 数组中的所有 7 个城市填充下拉菜单。但是,我目前正在尝试通过等待未正常工作的城市数组中的空值来结束 while() 循环,因此我需要帮助确定 JS 代码中 $florida[] 数组的大小,以便我可以结束 while() 循环并停止填充下拉菜单。
非常感谢任何帮助或提示!