我正在为我的网站创建一个注册表。在我的注册表中,有两个选择框来选择用户的地区和城市。所以我需要这样做,当用户选择他们的地区时,然后自动显示城市选择框,其中包含与上述所选地区相关的城市。为此,我使用了AJAX和PHP。我使用 findcity.php 页面在我的注册.php页面中显示城市。我的问题是当我尝试从注册.php页面获取城市 ID 时,我无法获得它。我需要将其他数据从注册.php页面发送到数据库。
从我的注册.php页面
<div>
<label for="district">District <img src="../images/required_star.png" alt="required" /> : </label>
<?php
require_once ('../includes/config.inc.php');
require_once( MYSQL2 );
$query="select * from district order by district_id";
$result = mysqli_query( $dbc, $query);
echo '<select name="district" class="text" onChange="getCity(' . "'" . 'findcity.php?district=' . "'" . '+this.value)">';
echo '<option value="">-- Select District --</option>';
while( $row = mysqli_fetch_array($result, MYSQLI_NUM)) {
echo '<option value="' . $row[0] . '"';
// Check for stickyness:
if ( isset( $_POST['district']) && ( $_POST['district'] == $row[0] ))
echo ' selected="selected"';
echo " >$row[1]</option>";
}
echo '</select>';
?>
</div>
<div>
<label for="city">City <img src="../images/required_star.png" alt="required" /> : </label>
<input type="hidden" name="reg_locationid" id="reg_locationid" value="56" />
<div id="citydiv" style="position: relative; top: -14px; left: 130px; margin-bottom: -26px;">
<select name="city" class="text">
<option>-- Select City --</option>
</select>
</div>
</div>
这是 FindCity.php 页面
<?php
$districtId=$_GET['district'];
require_once ('../includes/configaration.inc.php');
require_once( MYSQLCONNECTION );
$query="select city_id, city_name from city2 where district_id=$districtId";
$result=mysqli_query( $dbc, $query);
echo '<select name="city" class="text">
<option>-- Select City --</option>';
while($row=mysqli_fetch_array($result, MYSQLI_NUM)) {
echo '<option value="' . $row[0] . '"';
// Check for stickyness:
if ( isset( $_POST['city']) && ( $_POST['city'] == $row[0] )) {
echo ' selected="selected"';
//echo '<input type="hidden" name="city" value="' . $row[0] . '"';
}
echo " >$row[1]</option>";
}
echo '</select>';
?>
这是我的 Ajax 函数
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCity(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
echo '<select name="district" class="text" onChange="getCity(' .
''findcity.php?district='+this.value+'&city='' .
'+document.getElementsByName('city')[0].value)">';
或按照学习者的建议使用会话。
此外,如果你从HTML中提取JavaScript,代码会不那么丑陋......