我真的很新的PHP和ajax,我正在閱讀很多關於如何進行登錄而不刷新頁面的教程,這段代碼不起作用我不知道爲什麼,我所做的就是使用ajax傳遞用戶名和密碼,但是當我點擊botton時什麼也沒有發生。登錄不刷新頁面
但不是使用ajax我指向我的表單方向checklogin.php工作正常。
這是形式的代碼,其中包括Ajax代碼:
<script type="text/javascript">
function validLogin(){
var username=$('#username').val();
var password=$('#password').val();
var dataString = 'username='+ username + '&password='+ password;
$.ajax({
type: "POST",
url: "checklogin.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
$("#flash").hide();
if(result=='correct'){
window.location='index.php';
}else{
$("#errorMessage").html(result);
}
}
});
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
</script>
<label></label><input type="text" name="username" id="username" value="<?php echo $submitted_username; ?>" placeholder="Username...."/>
<label></label><input type="password" name="password" id="password" value="" placeholder="Password...."/><br>
<button name="submit" value="Submit" class="button" onClick="validLogin()">Login </button>
此標識的checklogin.php代碼
<?php
require("finalphp/connect.php");
$submitted_username = '';
$query = " SELECT id, username, password, salt FROM users WHERE username = :username ";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
header("Location: index.php");
die("Redirecting to: index.php");
}
else
{
print("Login Failed.");
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
?>
在'$ login_ok'你正在重定向。那麼爲什麼你需要AJAX?你可以直接提交,不是嗎?您正在AJAX中檢查「正確」,但從未將其設置在您的PHP中。 –