我有一个脚本,当用户经过验证时,他/她会被带到 Home.php
。目前 Home.php
没有做太多事情。但在左下角我有一个注销按钮。正如您所知,当用户单击此按钮时,他希望他的 session 被销毁并被重定向到登录页面。不幸的是,您无法在 php
中创建点击监听器。我浏览了一个小时寻找解决方案,但一直找不到正确的关键词或其他东西。
这是我的代码
编辑:您只需要从 Home.php
中读取一些代码,只有当有人不确定自己的答案时想要运行代码
Index.php
(登录页面)
<?php
session_start();
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
if (isset ($_POST["Username"])&& isset($_POST["Password"]))
{
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$_SESSION["username"] = $Username;
$DB_Check = " SELECT * from users Where username = '".$Username."' and password = '".$Password."' " ;
$result = mysql_query($DB_Check);
if(mysql_fetch_assoc($result) === false){
$error = "invalid username or password";
}else{
header( 'Location: Home.php' ) ;
}
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Index.css"/>
<title>Login</title>
</head>
<body>
<div id="main">
<div class="messages">
<?php
if(isset($error))
echo $error; ?>
</div>
<form action="Index.php" method="post">
<h5>Diary Name:</h5>
<input name="Username" type="text"/>
<h5>Password:</h5>
<input name="Password" type="password"/>
</br>
</br>
</br>
<input name="login" type="submit"/>
</form>
<p>Click <a href="Register.php">HERE </a>to register.</p>
</div>
</body>
</html>
Home.php
<?php
session_start();
echo "Username = " . $_SESSION["username"] . " !";
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
if (isset($_POST["entry"])){
$entry = $_POST["entry"];
$submission = "INSERT INTO `virtualdiary`.`entries` (`entry`) VALUES ('". $entry . "')";
mysql_query($submission);
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Home.css"/>
<title>Home</title>
</head>
<body>
<h1>Entry: </h1>
<form method="post" action="Home.php">
<textarea name="entry" rows="24" cols="87">
<?php
if (isset($_POST["entry"])){
echo $entry;
}
?>
</textarea>
</br>
</br>
<input name="submit" type="submit"/>
</form>
<button id="LogOut"><a href="Index.php">Log Out</a></button>
</body>
</html>
根据我通过搜索发现的内容,我需要一个带有 ajax 调用的 Home.js
文件。我对 Ajax 不太了解,所以我可能需要粘贴代码或非常生硬的教程。
谢谢
最佳答案
您可以将注销href更改为/Logout.php,并在Logout.php中有
<?php
session_start();
session_destroy();
header('Location: /Index.php');
?>
这只会破坏用户当前 session ,然后将用户重定向回 Index.php 页面。
AJAX 方式是(使用 jQuery,我不记得 ajax 调用的普通 JS 语法)
$.ajax({
type: 'GET',
url: '/Logout.php',
success: function(msg) {
if (msg == 'loggedOut') {
window.location.href = 'Index.php';
}
}
});
然后你需要更改 Logout.php,而不是标题行,使其成为 echo/die/print loggedOut
(或者一个 json 字符串,这可能会更好,但这是只是一个例子)。
关于javascript - 需要 Ajax 调用来销毁 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24033291/