效果描述
- 點擊「編輯」連結 → 文字區塊變為 `
- 編輯完成點擊外部或失焦 → AJAX POST 送往後端
- 成功後自動更新顯示區塊,無需重整頁面
完整前端代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Inline Edit Demo</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.mainbox { width: 400px; margin: 50px auto; font-family: Arial, sans-serif; }
.text_wrapper { border: 1px solid #0099cc; padding: 10px; min-height: 60px; background: #f9f9f9; }
.edit_link { float: right; color: #0099cc; cursor: pointer; margin-bottom: 5px; }
.editbox { width: 100%; height: 80px; border: 1px solid #0099cc; padding: 5px; font-family: inherit; font-size: 14px; box-sizing: border-box; display: none; }
.edit { display: none; }
</style>
</head>
<body>
<div class="mainbox">
<a href="#" class="edit_link">編輯</a>
<div class="text_wrapper">初始內容:這是一段可編輯的文字...</div>
<div class="edit"><textarea class="editbox"></textarea></div>
</div>
<script>
$(function() {
var $wrapper = $('.text_wrapper');
var $editBox = $('.editbox');
var $editArea = $('.edit');
var $link = $('.edit_link');
// 進入編輯模式
$link.click(function(e) {
e.preventDefault();
$wrapper.hide();
$editBox.val($wrapper.html()).show();
$editArea.show();
$editBox.focus();
});
// 點擊編輯區外部 → 送出儲存
$(document).mouseup(function(e) {
if (!$editArea.is(e.target) && $editArea.has(e.target).length === 0) {
if ($editArea.is(':visible')) {
saveContent();
}
}
});
// 編輯區內部點擊不觸發儲存
$editBox.mouseup(function(e) { e.stopPropagation(); });
function saveContent() {
var content = $editBox.val().trim();
if (!content) return; // 空內容不送
$.ajax({
type: 'POST',
url: 'update_profile_ajax.php',
data: { data: content },
cache: false,
dataType: 'json',
success: function(res) {
if (res.success) {
$wrapper.html(content).show();
} else {
alert('儲存失敗:' + (res.error || '未知錯誤'));
}
},
error: function() {
alert('網路錯誤,請稍後再試');
},
complete: function() {
$editArea.hide();
}
});
}
});
</script>
</body>
</html>
後端 PHP (update_profile_ajax.php)
<?php
header('Content-Type: application/json; charset=utf-8');
require_once 'db.php'; // PDO 連線
$input = isset($_POST['data']) ? trim($_POST['data']) : '';
if ($input === '') {
echo json_encode(['success' => false, 'error' => '內容不可為空']);
exit;
}
try {
$pdo = getPDO(); // 你的 PDO 實例函式
$stmt = $pdo->prepare("UPDATE users SET email = ? WHERE user_id = 1");
$stmt->execute([$input]);
echo json_encode(['success' => true]);
} catch (PDOException $e) {
error_log($e->getMessage());
echo json_encode(['success' => false, 'error' => '資料庫錯誤']);
}
安全性強化 (必要)
| 風險 | 對策 |
| SQL Injection | **參數化查詢 (PDO Prepared Statements)**,絕不拼接字串 |
| XSS | 輸出時 `htmlspecialchars()`,或前端用 `.text()` 而非 `.html()` |
| CSRF | 表單加入 CSRF Token,AJAX 標頭驗證 |
| 權限繞過 | 後端驗證登入狀態、資源擁有權 |
原始碼改進重點 (對比原文)
- ✅ 使用 jQuery 3.x、ES6 語法
- ✅ 事件委派 + `stopPropagation` 替換巢狀 `mouseup`
- ✅ JSON 回傳格式、錯誤處理完整
- ✅ **PDO 參數化查詢** 修正原文 `mysql_escape_string` + 字串拼接的嚴重注入漏洞
- ✅ 輸入修剪、空值攔截
- ✅ CSS 現代化 (box-sizing、flex 可選)