W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
在 PHP 中,AJAX 可用來(lái)與數(shù)據(jù)庫(kù)進(jìn)行交互式通信。本節(jié)介紹了這種交互式通信。
下面的實(shí)例將演示網(wǎng)頁(yè)如何通過(guò) AJAX 從數(shù)據(jù)庫(kù)讀取信息:
在上面的實(shí)例中,我們使用的數(shù)據(jù)庫(kù)表如下所示:
id | FirstName | LastName | Age | Hometown | Job |
---|---|---|---|---|---|
1 | Peter | Griffin | 41 | Quahog | Brewery |
2 | Lois | Griffin | 40 | Newport | Piano Teacher |
3 | Joseph | Swanson | 39 | Quahog | Police Officer |
4 | Glenn | Quagmire | 41 | Quahog | Pilot |
當(dāng)用戶在上面的下拉列表中選擇某位用戶時(shí),會(huì)執(zhí)行名為 "showUser()" 的函數(shù)。該函數(shù)由 "onchange" 事件觸發(fā):
<html>
<head>
<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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
showUser() 函數(shù)會(huì)執(zhí)行以下步驟:
上面這段通過(guò) JavaScript 調(diào)用的服務(wù)器頁(yè)面是名為 "getuser.php" 的 PHP 文件。
"getuser.php" 中的源代碼會(huì)運(yùn)行一次針對(duì) MySQL 數(shù)據(jù)庫(kù)的查詢,然后在 HTML 表格中返回結(jié)果:
<?php
$q=$_GET["q"];
$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_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>";
mysqli_close($con);
?>
解釋:當(dāng)查詢從 JavaScript 發(fā)送到 PHP 文件時(shí),將發(fā)生:
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: