
使用 jQuery Ajax 從 MySQL 檢索數(shù)據(jù)
為了使用 jQuery Ajax 從 MySQL 數(shù)據(jù)庫檢索數(shù)據(jù),必須遵循這些步驟:
1.創(chuàng)建 Ajax 請求:
利用 $.ajax() 函數(shù)建立 Ajax 請求。指定類型 (GET/POST)、URL(發(fā)送請求的位置)和 dataType(預期響應格式)。收到成功響應后,將執(zhí)行成功函數(shù)。
2.建立 MySQL 連接:
對于 MySQL 連接,請使用 mysqli 擴展。使用 mysqli_connect() 建立連接。
3.執(zhí)行數(shù)據(jù)庫查詢:
使用 mysqli_query() 函數(shù)運行查詢以從 MySQL 表中獲取數(shù)據(jù)。該查詢將負責提取所需的記錄。
4.顯示檢索到的數(shù)據(jù):
使用循環(huán)迭代結果集并以結構化方式顯示數(shù)據(jù)??紤]使用表格來表示數(shù)據(jù)。
示例代碼:
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "GET",
url: "display.php",
dataType: "html",
success: function(response) {
$("#responsecontainer").html(response);
}
});
});
});
</script>
<body>
<button>
<?php
$con = mysqli_connect("localhost", "root", "");
mysqli_select_db($con, "samples");
$result = mysqli_query($con, "SELECT * FROM student");
echo "<table border='1'>";
echo "<tr><th>Roll No</th><th>Name</th><th>Address</th><th>Stream</th><th>Status</th></tr>";
while ($row = mysqli_fetch_row($result)) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
echo "</table>";
?>
按照這些說明并利用提供的代碼片段,您可以成功檢索并使用 jQuery Ajax 顯示 MySQL 數(shù)據(jù)庫中的數(shù)據(jù)。
以上是如何使用 jQuery Ajax 檢索 MySQL 數(shù)據(jù)?的詳細內(nèi)容。更多信息請關注PHP中文網(wǎng)其他相關文章!