AJAX 数据库实例
AJAX可以用于与数据库的交互通信。
AJAX 数据库实例
以下实例将演示网页如何使用AJAX从数据库中获取信息:
实例说明-showCustomer() 函数
当用户在上面的下拉列表中选择客户时,将执行名为"showCustomer()"的函数。此函数由"onchange"事件触发:
showCustomer
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState
== 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML
= this.responseText;
}
};
xhttp.open("GET",
"getcustomer.php?q="+str, true);
xhttp.send();
}
showCustomer() 函数执行以下操作:
- 检查是否选择了客户
- 创建XMLHttpRequest对象
- 创建要在服务器响应就绪时执行的函数
- 将请求发送到服务器上的文件
- 注意,参数(q)被添加到URL中(带有下拉列表的内容)
AJAX服务器页面
上面JavaScript调用的服务器上的页面是一个名为"getcustomer.php"的PHP文件。
"getcustomer.php" 中的源代码对数据库运行查询,并在HTML表中返回结果:
<?php
$mysqli = new mysqli("servername", "username",
"password", "dbname");
if($mysqli->connect_error) {
exit('Could not connect');
}
$sql = "SELECT customerid, companyname,
contactname, address, city, postalcode, country
FROM customers WHERE
customerid = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_GET['q']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($cid,
$cname, $name, $adr, $city, $pcode, $country);
$stmt->fetch();
$stmt->close();
echo "<table>";
echo "<tr>";
echo "<th>CustomerID</th>";
echo
"<td>" . $cid . "</td>";
echo "<th>CompanyName</th>";
echo "<td>" . $cname
. "</td>";
echo "<th>ContactName</th>";
echo "<td>" . $name . "</td>";
echo "<th>Address</th>";
echo "<td>" .
$adr . "</td>";
echo "<th>City</th>";
echo "<td>" . $city . "</td>";
echo "<th>PostalCode</th>";
echo "<td>" .
$pcode . "</td>";
echo "<th>Country</th>";
echo "<td>" . $country .
"</td>";
echo "</tr>";
echo "</table>";
?>