[英]php echo javascript alert() not working
我想在用戶注銷時顯示一個彈出消息,所以我使用
echo "<script>alert(\"You are logged out\");</script>";
但它不起作用。
下面是我的編碼。 我的編碼有什么邏輯問題嗎?
<?php
session_start();
if(isset($_SESSION['Username']) == "admin")
{
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
@import "../CSS/Style.css";
@import "../CSS/Admin.css";
</style>
<title>Admin Home Page</title>
</head>
<body>
<div class="body"></div>
<?php
if(isset($_GET['id']) == "logout")
{
session_destroy();
echo "<script>alert(\"You are logged out\");</script>";
header("Location: ..\Main.php");
}
else
{
?>
<div class="menu">
<a href="ManageStaff.php">Manage Staff</a>
</div>
<div class="menu2">
<a href="ManageAccount.php">Manage Account</a>
</div>
<div class="logout">
<a href="AdminHomePage.php?id=logout">Logout</a>
</div>
<?php
}
}
else
{
?>
<center>
<p style="font-size:50px; font-weight:bold">Access Denied</p>
<p style="font-size:18px">Your request for this page has been denied because of access control</p>
</center>
<?php
}
?>
</body>
</html>
會話將被銷毀並重定向到 Main.php,只是alert()
不會出現。
您正在執行回顯,然后編寫重定位標頭。 如果您在 javascript 中重新定位(在用戶單擊警報之后),它可能會按照您期望的方式工作。
echo "<script>alert('You are logged out'); window.location.href='..\Main.php';</script>";
此外,您使用isset
的方式會導致問題,因為isset
返回 true 或 false(它檢查值是否存在),而不是返回值。
所以代替
if(isset($_SESSION['Username']) == "admin")
你需要做:
if(isset($_SESSION['Username']) && $_SESSION['Username'] == "admin")
header("Location: ..\\Main.php");
告訴瀏覽器在顯示頁面之前轉到另一個頁面...如果您希望用戶看到警報,請嘗試以下操作:
session_destroy();
echo "<script>";
echo "alert('You are logged out');";
echo "window.location = '../Main.php';"; // redirect with javascript, after page loads
echo "</script>";
使用這個它會解決你的問題!! 首先更改您的代碼
if(isset($_SESSION['Username']) == "admin")
{
到
if(!empty($_SESSION['Username']) && ($_SESSION['Username']=="admin")){
然后使用以下代碼
if(!empty($_GET['id']) && ($_GET['id']=="logout"))
{
session_destroy();?>
<script>
alert("You are logged out");
window.location.href='..\Main.php';
</script>
<?php }?>
試試吧,這一定行得通,並刪除php頭,替換為以下代碼。
echo "<script>alert('You are logged out');
location.href='..\Main.php';
</script>";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.