0

我有 2 个列表框,第一个用于国家,另一个用于城市,当用户选择一个国家时,它应该根据国家填充城市

县的数据库是( CountryID (pk), Code (pk), Name) city(CountryCode(pk),Name)

我创建了名为 reload 的 java 脚本函数,该函数加载页面 onChange 其工作良好,但城市列表中的问题没有填充国家项目..它仍然是空的..这是我的代码。我只是发布与问题相关的代码,它的页面太长了。此页面代码

dd-check.php

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

创建帐户.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>
4

1 回答 1

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>";
}
?>

在更改字段 country 时,它会使用该国家/地区名称调用 getcities.php....getcities.php 在 span 元素“result”中输出城市。这是您不需要重新加载页面的 ajax 方式。

于 2012-04-15T11:49:06.877 回答