当我运行以下javascript / php时,在警告json对象的'userid'属性时,我总是变得“ undefined”。但是,如果我将json对象字符串化,它将返回“ [{'userid':'1'}]”,这是正确的值。
如果我尝试访问json对象的正确名称,为什么会变得未定义?
这是我用来访问该对象的ajax:
$.ajax({
type: 'POST',
url: 'WebPHP/check_login.php',
contentType: "application/json; charset=utf-8",
data: finalObject,
async: false,
dataType: 'json',
success: function(data) {
if (data["result"] === false) {
alert("Invalid Email or Password");
} else {
var userID = data["result"];
alert(userID["userid"]);
var url = "AMessage.html";
alert(JSON.stringify(data["result"]));
}
}
});
和连接到数据库的PHP:
$json = file_get_contents('php://input');
$jsondata = json_decode($json);
$email = $jsondata - > email;
$password = $jsondata - > password;
$sql1 = " SELECT user_id as userid
FROM users
WHERE email = '$email'
AND password = '$password';
";
$result = mysqli_query($Thesisdb, $sql1) or die(mysqli_error($Thesisdb));
$rows = $result - > num_rows;
while ($row = $result - > fetch_assoc()) {
$response[] = $row;
}
$post_data = array();
if ($rows == 1) {
$post_data = array('result' => $response);
} else {
$post_data = array('result' => false);
}
echo json_encode($post_data);
mysqli_close($Thesisdb);
您无法访问该userid
属性,因为您的userID
变量包含一个数组-这就是[]
json响应中括号的含义:[{'userid':'1'}]
。尝试通过以下方式访问它:alert(userID[0]["userid"]);
。
更好的是,不要返回数组,因为$rows == 1
无论如何您都要进行检查。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句