我正在尝试使用php进行登录身份验证以匹配用户名和密码,并将其作为JSON对象回显。
表单将使用ajax发送,并且还会读取返回的JSON数据。这是我遇到麻烦的部分。
我的HTML看起来像这样:
<form id='logform' method='post' >
<label for="username">User Name: </label><input id='user_name' type='text' name='username' required placeholder='User Name' />
<label for="password">Password: </label><input type='password' placeholder="Password" name='password' id="password" required />
<input type="submit" name="submit" id="login" value="Log In" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
sendLogDetails.php:
<?php
include("dbconnect.php");
$numrows=0;
$password=$_POST['password'];
$username=$_POST['username'];
$query="select username, fname, lname, memcat from members where (username='$username' && password='$password')";
$link = mysql_query($query);
if (!$link) {
echo 3;
die();
}
$numrows=mysql_num_rows($link);
if ($numrows>0){ // authentication is successfull
$rows = array();
while($r = mysql_fetch_assoc($link)) {
$rows[] = $r;
}
$json=json_encode($rows);
echo $json;
} else {
echo 3; // authentication was unsuccessfull
}
?>
jQuery如下:
$("#login").click(function(){
username=$("#username").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "scripts/sendLogDetails.php",
data: "username="+username+"&password="+password,
success: function(html){
if(html=='true')
{
sessionStorage.setItem("user", $("#username").val());
}
else
{
$("#add_err").html("Wrong username or password");
}
},
});
return false;
});
上面的代码通过用户名和密码发送,当我在控制台日志中检查响应时,它会显示查询表中的数据。我想知道如何然后检索此数据以在会话存储中设置它???
答案 0 :(得分:1)
您的成功功能应如下success: function(data) {...
然后数据是JSON对象但是作为字符串。然后使用var object=JSON.parse(data)
检索实际对象。
然后,您可以通过处理新的object
变量
修改强>
success: function(data) {
try {
object = $.parseJSON(data);
} catch (e) {
// here you didn't get JSON back so we can assume it was an error, run your error code in here. data will still be the error number (3)
return false;
}
//run your code on the json object here.
}
通过对象循环
for (var key in object) {
//this if just checks if the key has a value, it is required
if (object.hasOwnProperty(key)) {
var value=object[key];
//then we need to put the key and the value into session storage
sessionStorage.setItem(key, value)
}
}