我有2个列表框,第一个是国家,另一个是城市 当用户选择一个国家时,它应该根据国家/地区填充城市
县的数据库是(CountryID(pk),Code(pk),Name) 市(COUNTRYCODE(PK),名称)
我创建了一个名为reload的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 :(得分: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元素“result”中的城市。这是ajax方式,您无需重新加载页面。