基於 jQuery Ajax + PHP + MySQL 實現的無刷新留言系統,核心流程:前端蒐集表單資料 → $.post() 非同步送至後端 → 後端寫入資料庫並回傳 JSON → 前端動態插入 DOM。本文提供完整模組化原始碼,適合初學者理解 Ajax 互動模式。
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
config.php<?php
// 資料庫配置
$cfg_dbhost = "localhost";
$cfg_dbuser = "root";
$cfg_dbpwd = "root";
$cfg_dbname = "ajaxdemo1";
$cfg_dbprefix = "";
// 建立連線(註:生產環境請改用 PDO/MySQLi)
$link = mysql_connect($cfg_dbhost, $cfg_dbuser, $cfg_dbpwd);
mysql_select_db($cfg_dbname);
mysql_query("SET NAMES utf8");
?>
⚠ 安全警示:mysql_* 函數已棄用(PHP 5.5+)並移除(PHP 7.0+),實務請使用 PDO 或 MySQLi 並採用預處理語句防止 SQL 注入。
deal.php<?php
header("Content-Type: application/json; charset=utf-8");
include "config.php";
// 簡易接收(生產環境務必驗證、過濾、轉義)
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$content = isset($_POST['content']) ? trim($_POST['content']) : '';
if ($name === '' || $content === '') {
echo json_encode(['status' => 0, 'msg' => '欄位不可為空']);
exit;
}
$sql = "INSERT INTO `test` (`name`, `content`) VALUES ('" . mysql_real_escape_string($name) . "', '" . mysql_real_escape_string($content) . "')";
$res = mysql_query($sql, $link);
if ($res) {
echo json_encode([
'status' => 1,
'name' => $name,
'content' => $content
]);
} else {
echo json_encode(['status' => 0, 'msg' => '資料庫寫入失敗']);
}
?>
index.php<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>無刷新留言板</title>
<style>
body { font-family: sans-serif; color: #555; font-size: 14px; }
#form { background: #dedede; padding: 10px 20px; width: 300px; margin-bottom: 20px; }
#show { background: #f6f6f6; padding: 10px 20px; width: 300px; }
#show p { margin: 6px 0; font-size: 13px; line-height: 22px; border-bottom: 1px dashed #cdcdcd; }
#show strong { color: #333; }
</style>
<script src="jquery-1.7.2.min.js"></script>
</head>
<body>
<div id="form">
<form id="suggest_form">
用戶名:<input type="text" name="name" id="name" /><br/>
內容:<textarea name="content" id="content"></textarea><br/>
<input type="button" value="發布" id="sub" />
</form>
</div>
<div id="show">
<?php
include "config.php";
$sql = "SELECT * FROM `test` ORDER BY `id` DESC";
$res = mysql_query($sql, $link);
while ($row = mysql_fetch_assoc($res)) {
echo "<p><strong>" . htmlspecialchars($row['name']) . "</strong> 發表了:" . htmlspecialchars($row['content']) . "</p>";
}
?>
</div>
<script>
$(function() {
$("#sub").click(function() {
var name = $("#name").val().trim();
var content = $("#content").val().trim();
if (!name || !content) {
alert("請填寫完整資料");
return;
}
$.post("deal.php", { name: name, content: content }, function(data) {
if (data.status) {
var html = "<p><strong>" + data.name + "</strong> 發表了:" + data.content + "</p>";
$("#show").prepend(html); // 新留言置頂
$("#name, #content").val(""); // 清空表單
} else {
alert("留言失敗:" + (data.msg || "未知錯誤"));
}
}, 'json').fail(function() {
alert("網路請求失敗,請檢查伺服器");
});
});
});
</script>
</body>
</html>
$.post(..., 'json') 自動解析回傳物件。prepend() 將新留言插入容器最前端,實現「最新在上」效果。htmlspecialchars() 轉義,防止腳本注入。.fail() 捕捉網路層錯誤,後端回傳 status: 0 處理業務邏輯錯誤。LIMIT offset, count)parent_id 欄位)php+ajax實現無刷新的新聞留言系統下載(請自行替換實際下載連結)
