2012-04-15 111 views
0

我有2個列表框,第一個爲國家,另一個爲城市 當用戶選擇一個國家時,它應該根據國家填充城市根據第一個列表的選定值填充下拉列表

全縣數據庫(CountryID(PK),碼分多址(PK),名稱) 城市(COUNTRYCODE(PK),名稱)

我創建Java腳本函數調用重新加載加載頁面的onChange 其工作不錯,但在城市名單中的問題是不填充國家項目..它仍然是空的.. 這裏是我的代碼。我只是發佈與問題有關的代碼,它的頁面太長。 此代碼爲

DD-check.php

<?php 
$cat = $_GET['Country']; 
$subcat = $_POST['City']; 
?> 

CreateAccount.php

<script language=JavaScript> 
function reload(form) 
{ 
    var val = form.Country.options[form.Country.options.selectedIndex].value; 
    self.location = 'Create_Account.php?country=' + val ; 
} 
</script> 

<form id="form2" method="post" enctype="multipart/form-data" action="dd-check.php"> 
<?php 
$Con= mysql_connect("localhost","root",""); 

if(!$Con) 
{ 
    die('Could not connect'.mysql_error()); 
} 

if(!mysql_selectdb("rlounge",$Con)) 
{ 
    die(mysql_error()); 
} 

@$cat = $_GET['Country']; 

if(strlen($cat) > 0 and !is_numeric($cat)) 
{ 
    echo "Data Error"; 
    exit; 
} 

$quer2 = "SELECT * FROM country"; 
$result = mysql_query($quer2); 
if(isset($cat) and strlen($cat) > 0) 
{ 
    $quer = mysql_query(" SELECT city.`Name` , `CountryCode` 
         FROM `city` , `country` 
         WHERE `CountryCode` = $cat 
         AND `Code` = `CountryCode` "); 
} 
else 
{ 
    $quer = mysql_query(" SELECT City.name 
         FROM `city` , `country` 
         WHERE `Code` = `CountryCode`"); 
} 
//$cat=$_GET['Country']; 
//$subcat=$_POST['City']; 
echo "<select name='Country' onchange=\"reload(this.form)\"><option value=''>Select  one</option>"; 
while($noticia2 = mysql_fetch_array($result)) 
{ 
    if($noticia2['Code'] == $cat) 
    { 
    echo "<option selected value='$noticia2[Code]'>$noticia2[Name]</option>"."<BR>"; 
    } 
    else 
    { 
    echo "<option value='$noticia2[Code]'>$noticia2[Name]</option>"; 
    } 
} 
echo "</select>"; 
echo "<select name='City'><option value=''>Select one</option>"; 
while($noticia = mysql_fetch_array($quer)) 
{ 
    echo "<option value='$noticia[CountryCode]'>$noticia[Name]</option>"; 
} 
echo "</select>"; 
?> 
</form> 

回答

0

像這樣創建的HTML文件。

<html> 
<head> 
<script type="text/javascript"> 
function getcities(str) 
{ 
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("result").innerHTML=xmlhttp.responseText; 
    } 
    } 
xmlhttp.open("GET","getcities.php?q="+str,true); 
xmlhttp.send(); 
} 
</script> 
</head> 
<body> 

<select name='Countries' onchange='getcities(this)'> 
</select> 
<p> <span id="result"></span></p> 

</body> 
</html> 

然後編寫PHP文件中像這樣

<?php 
$country=$_GET['q']; 
get cities from database 
while(cities) 
{ 
    echo "<option>".$city."</option>"; 
} 
?> 

這裏上改變場國家,它與這個國家的名字叫getcities.php .... getcities.php輸出城市span元素「結果'。這是你不需要重新加載頁面的Ajax方式。