我已经在 PHP 上完成了用户注册和登录系统。它工作正常,但现在我尝试使用 Ajax 发送 POST 请求以保持在同一页面中,并且 responseText 返回空。我尝试了一些我在类似问题中看到的解决方案,但没有一个对我有用。
这是我用来登录用户的php函数:
if(!empty($_POST)) {
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = ?
";
try {
$stmt = $db->prepare($query);
$stmt->bind_param("s", $_POST['username']);
$result = $stmt->execute();
}
catch(Exception $ex) {
die("Failed to execute the query");
}
// Is logged in?
$login_ok = false;
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row) {
// Hash the submitted password and compare it whit the hashed version that is stored in the database
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($n = 0; $n < 65536; $n++) {
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password']) {
$login_ok = true;
} else {
echo "Incorrect password";
}
}
if($login_ok) {
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo "Logged in";
} else {
echo "Login failed";
}
}
这是我的表单和 Ajax 函数:
<form action="" method="post">
<fieldset>
<legend>Login</legend>
<input type="text" name="username" placeholder="user" value="" />
<input type="password" name="password" placeholder="pass" value="" />
<input type="button" id="log" value="Login" onclick="log()"/>
</fieldset>
</form>
<script type="text/javascript">
function log(){
if (!window.XMLHttpRequest) return;
var url = "php/login.php",
req = new XMLHttpRequest();
req.open("POST", url);
req.send(null);
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
var response = req.responseText;
alert(response);
}
}
}
</script>
有任何想法吗?
编辑:我试图不使用 jQuery 顺便说一句。