AJAX可用于同数据库进行交互式通信
AJAX Database实例
showCustomer() 函数进行如下:
- 检查是否选取客户
- 创建 XMLHttpRequest 对象
- 创建当服务器响应就绪时执行的函数
- 向服务器上的文件发送请求
- 请注意,参数 q 被添加到 URL(带有下拉列- 表的内容)
<!doctype html>
<html>
<head>
<meta charset="gb2312">
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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 (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","/demo/getcustomer.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">请选择一个客户:</option>
<option value="1">Alibaba</option>
<option value="2">APPLE</option>
<option value="3">BAIDU</option>
<option value="4">Canon</option>
<option value="5">Google</option>
<option value="6">HUAWEI</option>
<option value="7">Microsoft</option>
<option value="8">Nokia</option>
<option value="9">SONY</option>
<option value="10">Tencent</option>
</select>
</form>
<br>
<div id="txtHint"><b>客户信息将在此处列出。</b></div>
</body>
</html>
AJAX 服务器页面
解释:当查询从 JavaScript 发送到 PHP 文件时,会发生以下情况:
- PHP 打开与 MySQL 服务器的连接
- 找到了正确的客户
- 创建一个 HTML 表,填充数据,并发送回“txtHint”占位符
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('MyServer','MyUser','MyPassword','Customers');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM customerslist WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result)) {
echo "<tr><th>CustomerID</th><td>" . $row['CustomerID'] . "</td></tr>";
echo "<tr><th>CompanyName</th><td>" . $row['CompanyName'] . "</td></tr>";
echo "<tr><th>ContactName</th><td>" . $row['ContactName'] . "</td></tr>";
echo "<tr><th>Address</th><td>" . $row['Address'] . "</td></tr>";
echo "<tr><th>City</th><td>" . $row['City'] . "</td></tr>";
echo "<tr><th>PostalCode</th><td>" . $row['PostalCode'] . "</td></tr>";
echo "<tr><th>Country</th><td>" . $row['Country'] . "</td></tr>";
}
echo "</table>";
mysqli_close($con);
?>