本文主要是通过ajax+php读取后台mysql数据库的数据,从而实现网页的局部更新。 创建一个简单的班级学员查询,html页面的代码为:
<html>
<head>
<script type="text/javascript">
function showStudent(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) //检查是否支持window.XMLHttpRequest
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getdata.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="" style="margin-top:15px;">
<label>请选择一个班级:
<select name="class" οnchange="showStudent(this.value)" style="font-family:Verdana, Arial, Helvetica, sans-serif;">
<option value="class1">一班</option>
<option value="class2">二班</option>
<option value="class3">三班</option>
<option value="class4">四班</option>
</select>
</label>
</form>
<br />
<div id="txtHint">学生信息将在此处列出 ...</div>
</body>
</html>
创建一个getdata.php的文件:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
mysql_select_db("test", $con);
mysql_query("set names utf8");
$sql="SELECT * FROM person WHERE class = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['sex'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
实现的效果如下: