[英]3 drop down using ajax and php
國家,州和地區共有3個下拉菜單。 當我從“國家/地區”下拉列表中選擇一個國家/地區時,我所做的就是,狀態下拉列表僅顯示與該國家/地區相鄰;當我選擇“州/地區”時,地區下拉列表僅顯示與該國家/地區下拉列表相鄰的地區。
我的home.php代碼是
<?php
include "config.php";
?>
<html>
<head>
<script type="text/javascript">
function showstate(str){
if (str == "") {
document.getElementById("state").innerHTML = "";
return;
}
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 && xmlhttp.status == 200) {
document.getElementById("state").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "state.php?country=" + str, true);
xmlhttp.send();
}
function showcity(str2){
if (str2 == "") {
document.getElementById("city").innerHTML = "";
return;
}
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 && xmlhttp.status == 200) {
document.getElementById("city").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "district.php?state=" + str2, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form >
Choose your country : <select name="country" onchange="showstate(this.value)"> <option>Select country </option>
<?php
$query = "SELECT DISTINCT country FROM area";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo"<option value =".$row[0]."> ".$row[0]."</option>";
}
?>
</select>
State : <select id="state" name="state" onChange="showcity(this.value)"> <option>Select state</option> </select>
District : <select id="city" name="city"> <option>Select district </option> </select>
</form>
</body>
</html>
和state.php是
<?php
include "config.php";
echo " <option>Select state </option> " ;
if(isset( $_GET['country']) )
{
$country = $_GET['country'];
}
$query = "SELECT DISTINCT state FROM area WHERE country = '".$country."' ";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
echo"<option value =".$row['state']."> ".$row['state']."</option>";
}
?>
而district.php是
<?php
include "config.php";
echo " <option>Select district </option> " ;
if(isset( $_GET['state']) )
{
$state = $_GET['state'];
}
$query = "SELECT DISTINCT district FROM area WHERE state = '".$state."' ";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
echo"<option value =".$row['district']."> ".$row['district']."</option>";
}
?>
一切都好。 但是問題是,當我選擇任何地區時都使用所有三個下拉菜單,如果再次在同一頁面中從國家下拉菜單中重新選擇國家,則地區不會保持不變。
在“更改國家/地區”並在調用ur ajax調用加載狀態之前,第1次將區域組合設為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.