Javascript 从mySQL中获取ID并使用php在ajax中设置localstorage
在某种程度上,我认为这是可行的,但在返回true之后,我希望将localstorage设置为mySQL查询中传递的id的值。我不确定如何传递这个消息,因为我的php目前只响应true或falseJavascript 从mySQL中获取ID并使用php在ajax中设置localstorage,javascript,jquery,mysql,ajax,local-storage,Javascript,Jquery,Mysql,Ajax,Local Storage,在某种程度上,我认为这是可行的,但在返回true之后,我希望将localstorage设置为mySQL查询中传递的id的值。我不确定如何传递这个消息,因为我的php目前只响应true或false <script type="text/javascript"> $(document).ready(function() { $('#loginButton').click(function(){ var username = $('#use
<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;
?>
$(文档).ready(函数(){
$(“#登录按钮”)。单击(函数(){
var username=$('#username').val();
var password=$('#password').val();
$.ajax({
类型:“POST”,
url:“login.php”,
cache:false,
数据:{用户名:用户名,密码:密码},
成功:功能(res){
开关(res){
case('true'):
警报(“真”);
打破
case('false'):
警报(“假”);
打破
}
}
});
返回false;
});
});
如果您想在使用AJAX时使用多个值进行响应,可以使用JSON
在php代码中应该是这样的(将其粘贴在$stmt->execute();
行之后,而不是if-else
construction):
然后在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。POST通常在您需要更改服务器的某些内容(数据库、会话、文件系统等)时使用,但当您只想获取一些数据时,最好使用get。然而,并没有人限制你们做你们想做的事,但我认为遵循标准更好
祝你好运 太棒了,这对我来说太棒了。我登上了邮轮。
$.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');
}
});