【发布时间】:2012-01-12 20:16:44
【问题描述】:
我有两个 MySQL 表:
- 'country' 字段:'country_id' 和 'country'
- 'city' 包含字段:'city_id'、'city'、'city_link' 和 'country_id'
我想构建一个 html 双下拉菜单,用户可以在其中选择一个“国家”,然后根据“国家”选择一个“城市”。此外,一旦选择了“城市”,我希望有一个使用 href 'city_link' 的 onClick 事件,它将用户带到另一个页面。
有两个文件(ajaxcalling.php):
<?
include("/connection.php");
$ID=$_REQUEST['country_id'];
$connect=mysql_connect($hostname_c, $username_c, $password_c);
echo 'Details:<select name="details" width="100">';
$result = mysql_db_query($database, "SELECT * FROM c_city WHERE country_id=".$ID);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<option value=".$row['city_id'].">".$row['city']."</option>";
}
echo '</select>';
mysql_close($connect);
?>
AND (dropdown.php)
<script>
function CreateXmlHttpObject() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();//creates a new ajax object
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
//this is for IE browser
}
catch(e){
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
//this is for IE browser
}
catch(e1){
xmlhttp=false;//error creating object
}
}
}
return xmlhttp;
}
function CategoryGrab(strURL)
{
var req = CreateXmlHttpObject(); // function to get xmlhttp object
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) { //data is retrieved from server
if (req.status == 200) { // which reprents ok status
document.getElementById('details').innerHTML=req.responseText;
//put the results of the requests in or element
}
else
{
alert("There was a problem while using XMLHTTP:\n");
}
}
}
req.open("GET", strURL, true); //open url using get method
req.send(null);//send the results
}
}
</script>
<?
include("connection.php");
$connect=mysql_connect($hostname_c, $username_c, $password_c)
or die ("Mysql connecting error");
echo '<table align="center"><tr><td><center><form method="post" action="">Category:
<select name="category"
onChange="CategoryGrab('."'".'ajaxcalling.phpcountry_id='."'".'+this.value);">';
$result = mysql_db_query($database, "SELECT * FROM c_country");
$nr=0;
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$nr++;
echo "<option value=".'"'.$row['country_id'].'" >'.$row['country']."</option>";
}
echo '</select>'."\n";
echo '<div id="details">Details:<select name="details" width="100" >';
$result = mysql_db_query($database, "SELECT * FROM c_city WHERE country_id=1");
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<option value=".$row['city_id'].">".$row['city']."</option>";
}
echo '</select></div>';
echo '</form></td></tr></table>';
mysql_close($connect);
?>
这是link
真的很感激一些帮助,因为我已经被困了一段时间......
【问题讨论】:
-
第 1 步)您是否正在访问 ajax 文件? 2) 在你的 onstatereadychange 中放置一个警报,看看你是否到达那里。
标签: php javascript mysql ajax