我有一个脚本,当用户获得验证时,他/她被带到Home.php
。目前Home.php
做得不多。但是在左下角我有一个退出按钮。正如您所知,当用户点击此按钮时,他希望他的会话被销毁,并将他重定向到登录页面。很遗憾,您无法在php
中创建点击监听器。我浏览了一个小时寻找解决方案,但我找不到正确的关键词或其他东西。
这是我的代码
编辑:您只需要从Home.php
读取一些代码,只有当someoe想要运行代码时才会知道他们的答案
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的第一件事,所以我可能需要代码粘贴或非常钝的教程。
感谢
答案 0 :(得分:3)
您可以将注销href更改为/Logout.php,并在Logout.php中更改
<?php
session_start();
session_destroy();
header('Location: /Index.php');
?>
这将简单地销毁用户当前会话,然后将用户重定向回Index.php页面。
AJAX的方式是(使用jQuery,我不记得ajax调用的vanilla 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字符串可能会更好,但这只是一个例子。