gpt4 book ai didi

javascript - 从mySQL获取ID并使用php在ajax中设置localstorage

转载 作者:行者123 更新时间:2023-11-29 08:12:45 26 4
gpt4 key购买 nike

我已经做到了这一点,但希望在返回 true 后,将 localstorage 设置为 mySQL 查询中传递的 id 值。我不确定如何传递这个,因为我的 php 目前只回显 true 或 false。

<script type="text/javascript">
$(document).ready(function() {
$('#loginButton').click(function(){

var username = $('#username').val();
var password = $('#password').val();

$.ajax({
type: "POST",
url: "login.php",
cache: false,
data: { username: username, password: password },
success: function(res) {
switch(res) {
case ('true'):
alert('true');
break;
case ('false'):
alert('false');
break;

}
}
});

return false;

});

});

</script>


<?php

$username = $_POST['username'];
$password = md5($_POST['password']);

if(!empty($username) && !empty($password)) {
$stmt = $conn->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindValue('username', $username);
$stmt->bindValue('password', $password);
$stmt->execute();

if($stmt->rowCount() == 0) {
echo 'false';
} else {
echo 'true';

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$user_id = $row['user_id'];
}
}
}

$conn = null;
?>

最佳答案

如果您想在使用 AJAX 时响应多个值,可以使用 JSON。

在 php 代码中应该是这样的(将其粘贴在 $stmt->execute(); 行之后,而不是 if-else 构造):

if($stmt->rowCount() == 0) {
echo json_encode(array('success' => false));
} else {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$user_id = $row['user_id'];

echo json_encode(array(
'success' => true,
'user_id' => $user_id
));
}

然后在 javascript 中,您应该指定您期望 JSON 作为响应。这是代码:

$.ajax({
type: "POST",
url: "login.php",
cache: false,
dataType: 'json', //this is where we specify JSON response
data: { username: username, password: password },
success: function(res) {
if (res.success) {
localStorage.setItem('user_id', res.user_id); //set user id to local storage
alert(res.user_id);
} else {
alert('false');
}
},
error: function() {
//this will trigger in case the server send invalid JSON (or other types of errors)
alert('false');
}
});

在这种情况下,我还建议使用 GET 方法而不是 POST 方法。当您需要更改服务器的某些内容(数据库、 session 、文件系统等)时,通常使用 POST,但是当您只想获取一些数据时,最好使用 GET。不过没有人限制你做你想做的事,但我认为遵循标准更好。

祝你好运!

关于javascript - 从mySQL获取ID并使用php在ajax中设置localstorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21266396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com