先建立一个页面ajax.html,包括一个下拉菜单,内容改变时传递给PHP页面查询数据库,反馈结果。
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
function select(obj)
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObect("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","data.php?q="+obj,true);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<select οnchange="select(this.value)">
<option selected="selected">nanchang</option>
<option>shanghai</option>
<option>beijing</option>
<option>shenzhen</option>
</select>
<div id="txtHint" align="center">
</div>
</body>
</html>
建立一个页面data.php,通过echo 打印输出的结果会显示回ajax.html
<?php
$a=$_GET["q"];
$link = mysql_connect("localhost","root","123456");
if(!$link)
{
die('数据库连接失败:'.mysql_error());
}
if(!mysql_select_db("test"))
{
die('数据库选择失败:'.mysql_error());
}
echo '<table width="100%" border="0">';
echo '<tr>';
echo '<th width="10%">ID</th>';
echo '<th width="10%">Name</th>';
echo '<th width="10%">Password</th>';
echo '</tr>';
$sql="select * from user where name='{$a}'";
$resultest=mysql_query($sql);
if($resultest&&mysql_num_rows($resultest)>0)
{
while (list($id,$name,$password)=mysql_fetch_row($resultest))
{
echo "<tr>";
echo '<th width="10%">ID</th>';
echo '<th width="10%">Name</th>';
echo '<th width="10%">Password</th>';
echo "</tr>";
}
}
?>