2012-04-15 104 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方式。