利用 HTML `` 實現瀏覽器端無 JS 跳轉,配合倒計時提升用戶體驗。
<?php
/**
* 頁面跳轉提示
* @param string $url 目標 URL
* @param string $message 提示信息
* @param int $seconds 延遲秒數
*/
function redirectWithMessage(string $url, string $message = '頁面跳轉中...', int $seconds = 3): void {
// 防止頭部已發送
if (headers_sent()) {
// 降級:JS 跳轉
echo "<script>setTimeout(() => location.href = " . json_encode($url) . ", {$seconds}000);</script>";
echo "<p>$message</p>";
exit;
}
// 發送狀態碼(可選)
// header('HTTP/1.1 302 Found'); // 臨時跳轉
// header("Refresh: $seconds; url=$url"); // HTTP 頭方式(不如 meta 兼容)
// 輸出完整 HTML
echo '<!DOCTYPE html>';
echo '<html><head><meta charset="UTF-8">';
echo '<title>頁面跳轉</title>';
echo '<meta http-equiv="refresh" content="' . $seconds . ';url=' . htmlspecialchars($url, ENT_QUOTES) . '">';
echo '<style>
body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#f5f5f5}
.box{background:#fff;padding:2rem;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,.1);text-align:center;max-width:400px}
h1{margin:0 0 1rem;color:#333}
.countdown{font-size:1.5rem;color:#007bff;font-weight:bold}
a{color:#007bff;text-decoration:none}
</style>';
echo '</head><body><div class="box">';
echo '<h1>' . htmlspecialchars($message) . '</h1>';
echo '<div class="countdown" id="cd">' . $seconds . '</div>';
echo '<p>如果瀏覽器未自動跳轉,請點擊 <a href="' . htmlspecialchars($url, ENT_QUOTES) . '">這裡</a></p>';
echo '</div>';
echo '<script>
let s = ' . $seconds . ';
const el = document.getElementById("cd");
const timer = setInterval(() => {
s--;
if (s > 0) el.textContent = s;
else { clearInterval(timer); }
}, 1000);
</script>';
echo '</body></html>';
exit;
}
// 使用示例
// redirectWithMessage('/dashboard', '登錄成功,正在跳轉...', 2);
?>
AJAX 不能直接跟隨 `meta refresh`,需返回 JSON 讓前端處理:
<?php
function ajaxRedirect(string $url, string $message = '操作成功'): void {
header('Content-Type: application/json; charset=UTF-8');
echo json_encode([
'code' => 0,
'msg' => $message,
'redirect' => $url,
]);
exit;
}
// 前端 JS
fetch(url, {method:'POST', body:formData})
.then(r => r.json())
.then(data => {
if (data.code === 0 && data.redirect) {
setTimeout(() => location.href = data.redirect, 1500);
showToast(data.msg);
}
});
| 場景 | 狀態碼 | PHP 代碼 |
|---|---|---|
| 表單提交成功,重定向到列表頁 | 303 See Other | header('Location: /list', true, 303); |
| 登錄成功,跳轉儀表盤 | 302 Found | header('Location: /dashboard', true, 302); |
| 永久遷移(SEO 權重傳遞) | 301 Moved Permanently | header('Location: /new-url', true, 301); |
| 需顯示提示信息再跳轉 | 200 OK + meta refresh | redirectWithMessage() |
`redirectWithMessage()` 封裝了「友好提示 + 倒計時 + 降級鏈接 + JS 倒計時動畫」,開箱即用。AJAX 場景返回 JSON 由前端控制跳轉。核心原則:**輸出前調用、URL 轉義、狀態碼語義化**。