0
我已經在PHP上完成了用戶註冊和登錄系統。它工作正常,但現在我試圖發送POST請求與Ajax留在同一頁面,並且responseText返回空。我已經嘗試了一些我在類似問題中看到的解決方案,但他們都沒有爲我工作。Ajax&PHP,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 btw。
它看起來不像你發送任何POST數據在該Ajax請求。因此你的第一個PHP條件不符合。 'if(!empty($ _ POST))'。嘗試粘貼一個「其他回聲」沒有POST數據「;'結束雙重檢查。 – diggersworld
你是對的。我從另一個請求中複製了ajax代碼,並忘記了發佈數據。我不能相信我花了兩個小時試圖解決它,並沒有看到-_-。謝謝 – nahl