我有一个验证登录脚本的 AJAX 脚本,当用户输入不正确的数据时,会出现错误消息,但是当用户输入正确的数据时,新页面会加载到错误消息空间中。我知道问题出在哪里,我只是不知道如何解决它。
下面是登录脚本和检查登录脚本
登录.php
<table class="loginTable" align="center">
<tr>
<td>
Email:
</td>
<td>
<input type="text" name="email" id="email"/>
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type="password" name="password" id="password"/>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<span id="ErrorMessage"></span>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<!--Keep me logged in? <input type="checkbox" name="keeploggedin" /><br /><br />-->
<input id="loginButton" type="button" name="login" value="Login" onclick="processLogin()"/>
</td>
</tr>
</table>
<script>
function processLogin()
{
var xmlhttp;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ErrorMessage").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","checklogin.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("email=" + email + "&password=" + password);
}
</script>
检查登录.php
<?php
session_start();
//Login Script
//Variables
$email = $_REQUEST['email'];
$userPassword = $_REQUEST['password'];
//$keeploggedin = $_REQUEST['keeploggedin'];
require_once("dbdetails.php");
// Create Mysqli object
$db = new mysqli($hostname, $username, $password, $database);
// Create statement object
$stmt = $db->stmt_init();
// Create a prepared statement
if($result = $stmt->prepare("SELECT u.UserFirstName, u.UserSurname, u.UserID FROM user u WHERE u.UserEmail = ? AND u.UserPassword = ?")) {
// Bind your variables to replace the ?s
$stmt->bind_param('ss', $email, $userPassword) or die(errorCodes($stmt->errno));
//$row -> fetch_array(MYSQLI_ASSOC);
// Execute query
$stmt->execute() or die(errorCodes($stmt->errno));
$stmt->bind_result($fname, $sname, $userID);
$stmt->store_result();
$count = $stmt->num_rows;
if($count == 1){
while($row = $stmt->fetch()) {
// Register $email, $password, $firstname, $surname, create logged_in session and redirect to file "projects.php"
$_SESSION['email'] = $email;
$_SESSION['password'] = $userPassword;
$_SESSION['firstname'] = $fname;
$_SESSION['surname'] = $sname;
$_SESSION['userID'] = $userID;
$_SESSION['LoggedIn'] = 'true';
$_SESSION['loginCount'] = 0;
header("location:projects.php");
}
}
else {
//$_SESSION['loginCount'] += 1;
//header("location:loginPage.php");
//echo("<script type='text/javascript'>\n");
//echo("changeError();\n");
//echo("</script>");
echo("Username and Password mismatch, please try again");
}
// Close statement object
$stmt->close();
}
function errorCodes($aErrorCode) {
echo("Error " . $aErrorCode . " has occured");
}
?>