AJAX 可用于与数据库进行交互通信。
以下示例将演示网页如何使用 AJAX 从数据库获取信息:
当用户在上面的下拉列表中选择客户时,会调用一个函数showCustomer()
被执行。该功能由以下条件触发onchange
事件:
function showCustomer(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("txtHint").innerHTML = this.responseText;
}
xhttp.open("GET", "getcustomer.html?q="+str);
xhttp.send();
}
这个showCustomer()
函数执行以下操作:
上面的 JavaScript 调用的服务器上的页面是一个名为 "getcustomer.html" 的 PHP 文件。
"getcustomer.html" 中的源代码对数据库运行查询,并在 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>";
?>
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!