PHP 是伺服器端語言,無法直接產生瀏覽器原生對話框。常見做法是輸出 JavaScript 程式碼,利用 alert()、confirm() 或自訂 Modal 實現提示。本文介紹兩種基本輸出模式與現代替代方案。
<?php
$message = '操作成功!';
// 輸出 JavaScript alert
echo "<script>alert('" . addslashes($message) . "');</script>";
?>
適用場景:簡單通知、除錯、導向前頁面。
<?php
$message = '資料已儲存';
$redirectUrl = 'index.php';
echo "<script>";
echo "alert('" . addslashes($message) . "');";
echo "location.href = '" . addslashes($redirectUrl) . "';";
echo "</script>";
?>
關鍵點:location.href 在使用者點確定後執行導向。
直接輸出變數極易造成 XSS,務必轉義:
<?php
function jsAlert(string $message, ?string $redirect = null): void {
$safeMsg = json_encode($message, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
$script = "alert($safeMsg);";
if ($redirect !== null) {
$safeUrl = json_encode($redirect, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
$script .= "location.href = $safeUrl;";
}
echo "<script>$script</script>";
}
// 使用
jsAlert('歡迎 用戶', 'dashboard.php');
?>
json_encode()配合JSON_HEX_*旗標,能完整編碼 HTML/JS 特殊字元,比addslashes()更安全。
傳統 alert() 阻塞 UI、樣式無法客製、行動裝置體驗差。建議改用:
<!-- 引入 CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// PHP 端輸出資料屬性或內聯變數
const msg = = json_encode($message, JSON_HEX_TAG) ?>;
const url = = json_encode($redirectUrl ?? '', JSON_HEX_TAG) ?>;
Swal.fire({
icon: 'success',
title: '完成',
text: msg,
confirmButtonText: '確定'
}).then(() => {
if (url) window.location.href = url;
});
</script>
<script src="https://cdn.jsdelivr.net/npm/toastr@2.1.4/build/toastr.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastr@2.1.4/build/toastr.min.css">
<script>
toastr.success('= json_encode($message, JSON_HEX_TAG) ?>');
// 不阻塞、自動消失、可堆疊
</script>
現代專案建議:
{"success": true, "message": "操作成功", "redirect": "/list"}<?php
// API 回應範例
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'message' => '會員建立成功',
'redirect' => '/members',
'data' => ['id' => 123]
]);
?>
| 方法 | 優點 | 缺點 | 建議場景 |
|---|---|---|---|
| inline alert() | 零依賴、最簡單 | 阻塞、醜、XSS 風險 | 快速原型、後台簡單提示 |
| alert + location.href | 可導向 | 同上 | 表單送出後導向 |
| SweetAlert2 / Toast | 美觀、非阻塞、可客製 | 需引入 JS/CSS | 正式專案、使用者面向頁面 |
| JSON API + 前端元件 | 架構乾淨、可測試、SPA 友善 | 需前端框架配合 | 現代專案標準做法 |
選擇適合專案階段的方案,但務必記住:所有輸出到 JS 的變數必須經過 json_encode() 編碼。