傳統 PHP 直接輸出 `` 雖簡單,但違反關注點分離、阻塞渲染、難以維護。本文提供現代化替代方案:AJAX + 前端元件、Session Flash 訊息、API 統一錯誤格式。
<?php
function alert(string $message, string $url = '', bool $showAlert = true, string $title = '提示'): never {
echo "$title ";
echo "";
echo "";
exit;
}
// 使用
alert('資料儲存成功', '/dashboard');
alert('權限不足', '', true, '錯誤');
缺點:混雜 HTML/JS/PHP、無法單元測試、阻塞輸出、CSP 策略可能阻擋 inline script、手機版 alert 體驗差。
<?php
// 控制器
session_start();
$_SESSION['flash'] = ['type' => 'success', 'message' => '儲存成功'];
header('Location: /dashboard');
exit;
// 版面模板
<?php if (!empty($_SESSION['flash'])): ?>
<div class="alert alert-= h($_SESSION['flash']['type']) ?>" id="flash-msg">
= h($_SESSION['flash']['message']) ?>
</div>
<?php unset($_SESSION['flash']); ?>
<?php endif; ?>
<script>
// 3 秒自動淡出
setTimeout(() => {
const el = document.getElementById('flash-msg');
if (el) el.style.transition = 'opacity 0.5s', el.style.opacity = '0';
}, 3000);
</script>
<?php
// api_response.php
function apiResponse(int $code, string $message, mixed $data = null, int $httpCode = 200): never {
http_response_code($httpCode);
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'code' => $code, // 業務代碼:0=成功, 1001=驗證失敗, 1002=權限不足...
'message' => $message,
'data' => $data,
'timestamp' => time(),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
// 使用
if (!$validator->passes()) {
apiResponse(1001, '驗證失敗', $validator->errors(), 422);
}
apiResponse(0, '操作成功', ['id' => $newId]);
// axios 攔截器
axios.interceptors.response.use(
res => res.data, // 直接回傳 data
err => {
const resp = err.response?.data;
if (resp?.message) {
// 使用優雅通知庫:Toast, SweetAlert2, ElMessage, Toastr
ElMessage.error(resp.message);
}
return Promise.reject(err);
}
);
// 元件中
async function submitForm() {
try {
const { data } = await api.post('/user', formData);
ElMessage.success(data.message);
router.push('/dashboard');
} catch (e) { /* 攔截器已處理 */ }
}
若不想寫獨立前端,可用: