AJAX 可用来与数据库进行交互式通信。
<html>
<head>
<script src = "selectuser.js"></script>
</head>
<body>
<form>
Select a User:
<select name = "users" onchange = "showUser(this.value)">
<option value = "1">Peter Griffin</option>
<option value = "2">Lois Griffin</option>
<option value = "3">Joseph Swanson</option>
<option value = "4">Angelo</option>
</select>
</form>
<p>
<div id = "txtHint"><b>User info will be listed here.</b></div>
<p>
</body>
</html>
var xmlHttp
function showUser(str){
xmlHttp = GetXmlHttpObject()
if(xmlHttp == null){
alert("Browser does not support Http Request!");
return;
}
var url = "getuser.php";
url = url + "?q=" + str;
url = url + "&sid=" + Math.random();
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
document.getElementById("txtHint").innerHTML = xmlHttp.responseText;
}
function GetXmlHttpObject()
{
var xmlHttp = null;
try{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
<?php
$q = $_GET['q'];
$con = mysql_connect("localhost", "root", "admin");
if (!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("angelo_one", $con);
$sql = "select * from User where id = '". $q . "'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Home</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] , "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>