我對 php 很陌生,我做了一些研究并嘗試了其他人的解決方案,但對我來說沒有用。我想在執行特定代碼后將用戶重定向到另一個頁面。我意識到沒有錯誤訊息,站點也沒有改變。所以我從代碼中洗掉了幾乎所有內容并將其放入一個小的 test.php 檔案中。同樣的問題仍然存在。
<!DOCTYPE html>
<html>
<body>
<h1>Tes2</h1>
<?php
// Execute some code here
sleep(10); // Give the user 10 seconds to read the output of my code
// redirect the user with php or trigger a JS script to do that
header("Window-target: _parent");
header("Location: https://www.w3schools.com/");
?>
</body>
</html>
期望:頁面應該執行主要的 php 腳本(通過注釋可視化)并觸發一個計時器。當計時器結束時,它應該將我重定向到“www.w3schools.com”。應該沒有錯誤或其他訊息。如果可能的話,重定向應該由 php 代碼完成(JS 是解決這個問題的可能方法,但我仍然需要在我的 php 代碼執行后啟動 JS 代碼)。
結果:頁面顯示并加載 html 代碼。該網站保持不變。沒有錯誤。
環境:在 Linux Mint(64 位)的 Chromium 版本 96.0.4664.45(Offizieller Build)上運行 該網站功能正常,確實按預期執行了 PHP 代碼,但不是這個。
是否有一種輕量級和通用的(對于大多數流行的瀏覽器)解決方案可以將用戶重定向到另一個頁面?
uj5u.com熱心網友回復:
必須在傳輸任何資料之前設定標頭,因此您不能將它們放在檔案中間。參考手冊:
請記住,必須在發送任何實際輸出之前呼叫header(),無論是通過普通的 HTML 標記、檔案中的空行還是來自 PHP。
因此,至少您需要將檔案重寫為:
<?php
header("Window-target: _parent");
header("Location: https://www.w3schools.com/");
?>
<!doctype html>
...
此外,永遠不要sleep()在 http(s) 回應中:該回應應該盡可能快地完成,無論它需要生成什么內容。Sleep 在(真的任何)PHP 代碼中都沒有位置。
uj5u.com熱心網友回復:
PHP 和 JS 的組合似乎是最簡單的解決方案。但這可能只是我的意見。我試圖盡可能好地記錄代碼,以便其他人可以理解它:
<?php
function redirect() { // Create some JS code which will pause for 3 seconds and execute the move function afterwards. This Function will redirect the user
echo "<script>";
echo "function move() {window.location.replace('http://www.w3schools.com');}";
echo "setTimeout(move, 3000);";
echo "</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Test2</h1>
<?php
echo "<p>You will be redirected after the code has been executed!</p>";
// Run actual code
redirect(); // Redirect using JS code
?>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/381335.html
標籤:javascript php 网络 网址 后端
