下面的實例將演示網頁如何通過 AJAX 從數據庫讀取信息:
本教程使用到的 Websites 表 SQL 文件:websites.sql。
當用戶在上面的下拉列表中選擇某位用戶時,會執行名為 "showSite()" 的函數。該函數由 "onchange" 事件觸發:
上面這段通過 JavaScript 調用的服務器頁面是名為 "getsite_mysql.php" 的 PHP 文件。
"getsite_mysql.php" 中的源代碼會運行一次針對 MySQL 數據庫的查詢,然后在 HTML 表格中返回結果:
getsite_mysql.php 文件代碼: ?php$q = isset($_GET[ q ]) ? intval($_GET[ q ]) : '';if(empty($q)) { echo '請選擇一個網站'; exit;$con = mysqli_connect('localhost','root','123456');if (!$con) die('Could not connect: ' . mysqli_error($con));// 選擇數據庫mysqli_select_db($con, test );// 設置編碼,防止中文亂碼mysqli_set_charset($con, utf8 );$sql= SELECT * FROM Websites WHERE id = ' .$q. ' ;$result = mysqli_query($con,$sql);echo table border='1' th ID /th th 網站名 /th th 網站 URL /th th Alexa 排名 /th th 國家 /th /tr ;while($row = mysqli_fetch_array($result)) echo tr ; echo td . $row['id'] . /td ; echo td . $row['name'] . /td ; echo td . $row['url'] . /td ; echo td . $row['alexa'] . /td ; echo td . $row['country'] . /td ; echo /tr ;echo /table ;mysqli_close($con);鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
|
新聞熱點
疑難解答