單一函數處理所有前端提示需求:訊息彈窗、導向、重新整理、關閉視窗、執行父視窗函數、延遲執行。
<?php
/**
* 通用 JS 提示與導向
*
* @param string $msg 提示訊息 (空字串不彈窗)
* @param string $type 動作類型: back|reload|close|function|URL
* @param string $target 目標視窗/函數名 (self|top|parent|functionName)
* @param int $delay 延遲毫秒 (100 立即執行)
*/
function alert($msg = '', $type = 'back', $target = '', $delay = 100) {
echo '<script>' . PHP_EOL;
if ($msg !== '') {
// 轉義單引號、換行
$msg = addslashes(str_replace(["\r\n", "\r", "\n"], ['\\n', '\\n', '\\n'], $msg));
echo "alert('{$msg}');" . PHP_EOL;
}
echo 'function _redirect(){' . PHP_EOL;
$win = ($target !== '') ? 'top' : 'self';
switch (strtolower($type)) {
case '#': // 不動作
break;
case 'back':
echo "{$win}.history.go(-1);" . PHP_EOL;
break;
case 'reload':
echo "{$win}.location.reload();" . PHP_EOL;
break;
case 'close':
echo "window.opener=null; window.close();" . PHP_EOL;
break;
case 'function':
// 執行父視窗/當前視窗函數
echo "var fn = new Function('return {$target}')(); fn();" . PHP_EOL;
break;
default:
// 視為 URL 導向
if ($type !== '') {
echo "{$win}.location.href = '{$type}';" . PHP_EOL;
}
}
echo '}' . PHP_EOL;
// Firefox setTimeout 相容處理
echo 'if (setTimeout("_redirect()", ' . $delay . ') === 2) { _redirect(); }' . PHP_EOL;
if ($delay == 100) echo '_redirect();' . PHP_EOL;
echo '</script>' . PHP_EOL;
exit;
}
| 呼叫 | 效果 |
|---|---|
alert('登入成功', 'reload') | 彈窗後重新整理當前頁 |
alert('資料已儲存', 'back') | 彈窗後返回上一頁 |
alert('', 'close') | 直接關閉彈出視窗 |
alert('完成', 'function', 'parent.refreshList') | 彈窗後呼叫父視窗 refreshList() |
alert('跳轉中...', '/admin/dashboard', '', 2000) | 2 秒後導向儀表板 |
addslashes 轉義單引號,但若輸出在 HTML 屬性中仍需 htmlspecialchars。建議改用 JSON 編碼:json_encode($msg, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP)。nonce 或 unsafe-inline,現代專案建議改用前端框架 Toast/Modal 組件,後端只回傳 JSON。<?php
// API 回傳 JSON
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'message' => '操作成功',
'redirect' => '/dashboard',
'action' => 'reload', // 或 'replace', 'back', 'close'
]);
// 前端 Vue/React/Alpine 接收後顯示 Toast 並執行對應動作