我正在忙于开发一个网站,该网站的右上角有一个登录框。我希望用户能够在不刷新的情况下登录同一页面。
好的,我已经开始工作了,但是我仍在努力登录后的过程,如下所示:
(HTML)
<li class="login"> <? if (!isset($_SESSION['logged_in'])) { include("isNotLoggedIn.php"); } else { include("isLoggedIn.php"); } ?> </li>
(PHP)
session_start(); $username = $_POST['username']; $password = $_POST['password']; if ($username == "admin" && $password == "XXX") { $_SESSION['logged_in'] = true; $_SESSION['user'] = $username; echo include("isLoggedIn.php"); } else { echo include("isNotLoggedIn.php"); }
(我的jQuery)
$("form#login").submit( function() { var usernameVal = $("input[name='username']").val(); var passwordVal = $("input[name='password']").val(); $.post("login.php",{username : usernameVal, password : passwordVal}, // callback function to receive feedback function(data) { $("li.login").html(data); }); return false; }); $("a[name='logout']").click( function() { $.post("logout.php", function(data) { $("li.login").html(data); }); });
(isLoggedIn.php)
Welcome, <? echo $_SESSION['user']; ?>!<br /> <a href="#">Add game</a><br /> <a href="#">Add player</a><br /><br /> <a href="#" name="logout">Log out</a>
(isNotLoggedIn.php)
<form method="post" id="login"> <input type="text" name="username" alt="Username" class="text" title="Username: Required" value="username" /><br /> <input type="password" name="password" alt="Password" class="text" title="Password: Required" value="password" /><br /> <input type="submit" name="submit" alt="Login" title="Login" value="Login" class="submit" /> </form>
登录过程可以正常工作,但是注销混乱。当我单击isLoggedIn.php中的Logout链接时,它注销了,但是我在文本输入上的jQuery和表单本身上的jQuery不再起作用。
有没有一种方法我必须刷新我的jQuery才能在替换的HTML上重新激活?任何帮助表示赞赏。
问候和TIA
只是为了详细说明redsquare的答案,您需要将jQuery更改为此…:
$(function() { /** ...What ever else you might have onload... **/ $("a[name='logout']").live('click',function() { // Now using the .live() event $.post("logout.php", function(data) { $("li.login").html(data); bind_login_submit(); // <---- Notice, this is new }); }); bind_login_submit(); // Call this function to initially bind the submit }); function bind_login_submit() { $("form#login").unbind('submit').bind('submit',function() { var usernameVal = $("input[name='username']").val(); var passwordVal = $("input[name='password']").val(); $.post("login.php",{username : usernameVal, password : passwordVal}, function(data) { $("li.login").html(data); }); return false; }); }