我正在做一个登录和用户管理项目,我正在学习 jQuery 和 Ajax。
我有基本功能,即用户登录,如果用户名和/或密码无效,则会出现错误的用户名和/或密码消息。
我想要实现的(我正在寻找方法)是登录成功后能够重定向到用户页面。(我不知道我是否必须从 php 来做,或者我可以使用 jQuery 来代替)。
这是我的 index.php:
<?php
require_once 'php/logOut.php';
session_start();
if(isset($_SESSION['userSession'])){
if(!empty($_SESSION['userSession'])){
header("Location: models/userPanel.php");
}
}
if (isset($_GET['logOut'])) {
logOut();
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<!-- CSS imports -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/main.css" />
<!-- JQuery include -->
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<!-- <script type="text/javascript" src="js/loginForm.js"></script> -->
<meta charset="utf-8">
<title>Login</title>
</head>
<body>
<!-- Navigation Bar content -->
<nav class="navBar">
<ul>
<li><a class="hover" href="index.php">Index</a></li>
</ul>
</nav>
<!-- Body content -->
<div class="bodyContainer">
<!-- Form -->
<div class="formContainer">
<p class="formTitle">Login form</p>
<form id="loginForm" method="post">
<div class="formDataContainer">
<div id="error"><!-- Error will be shown here ! --></div>
<label for="userMail"><span class="labelText">Email</span></label>
<input type="email" placeholder="Enter Username" name="userMail" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
<label for="psw"><span class="labelText">Password</span></label>
<input type="password" placeholder="Enter Password" name="psw" required autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
<button type="submit" id="btnLogin" name="btnLogin">Sing in</button>
</div>
</form>
</div>
</div>
<script>
$('#error').fadeOut();
$('form[id=\'loginForm\']').on('submit', function(e){
e.preventDefault();
$("#error").fadeOut();
var data = $(this).serialize();
$.ajax({
type: 'POST', url: 'php/loginProcess.php', data: data, beforeSend: function(){
$('#error').fadeOut();
$('#btnLogin').html('Sending ...');
}, success: function(response){
if (response == 'ok'){
$('#btnLogin').html('Signing In ...');
setTimeout(' window.location.href = "models/userPanel.php"; ', 4000);
}else{
$('#error').fadeIn(1000, function(){
$('#error').html(response);
$('#btnLogin').html('Sign In');
});
}
},
});
return false;
});
/* login submit */
</script>
</body>
</html>
而这个,我的 PHP 控制器:
<?php
session_start();
require_once 'dbConfig.php';
$query = "SELECT idUser, name, surname, mail, level, password
FROM users
WHERE mail = ? AND password = ?";
// TODO recoger datos
if(isset($_POST["userMail"]) && isset($_POST["psw"])){
if(!empty($_POST["userMail"]) && !empty($_POST["psw"])){
// TODO comprobamos la base de datos
// Clean obtained data
$userMail = $mysqli->real_escape_string(trim($_POST["userMail"]));
$passwd = $mysqli->real_escape_string(trim($_POST["psw"]));
// Crypt the Password
$password = md5($passwd);
// Attempt to prepare the query
if($stmt = $mysqli->prepare($query)){
if($stmt->bind_param("ss", $userMail, $password)){
$stmt->execute();
// Obtain the result
$result = $stmt->get_result();
// If there is no result, we will show an error message
if($result->num_rows === 0){
echo "Invalid username or password";
}else{
// If we have data, we will check again the obtained data
$row = $result->fetch_array();
if($row["mail"] === $userMail && $row["password"] === $password){
// If correct, we will log in the user
$_SESSION['userSession']['mail'] = $row['mail'];
$_SESSION['userSession']['name'] = $row['name'];
$_SESSION['userSession']['surname'] = $row['surname'];
// TODO redirect
}
}
$mysqli->close();
}else{
// TODO handle error
}
}
}
}
?>
如您所见,我在 PHP 控制文件中有一个用于重定向的 TODO,但我不知道该怎么做。我已经通过 jQuery 尝试了解决方案,但它们不起作用。
非常感谢您提前。
编辑
看到答案后,我尝试按照他们告诉我的代码执行代码,但现在重定向未正确执行。
$('#error').fadeOut();
$('form[id=\'loginForm\']').on('submit', function(e){
e.preventDefault();
$("#error").fadeOut();
var data = $(this).serialize();
$.ajax({
type: 'POST', url: 'php/loginProcess.php', data: data, beforeSend: function(){
$('#error').fadeOut();
$('#btnLogin').html('Sending ...');
}, success: function(response){
if (response == 'ok'){
$('#btnLogin').html('Signing In ...');
window.location("models/userPanel.php");
setTimeout(' window.location.href = "models/userPanel.php"; ', 4000);
}else{
$('#error').fadeIn(1000, function(){
$('#error').html(response);
$('#btnLogin').html('Sign In');
});
}
},
});
return false;
});
在 TODO 所在的行中,您必须添加如下内容:
编辑:这不起作用,因为标头位置是在 ajax 请求下完成的,而不是在用户页面上。为了在 ajax 调用之后重定向,必须在成功或完成 ajax 的一部分中完成 window.location: