[英]Javascript will not access json object
當我運行以下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
。
是的,正如#Jack所說,您無法訪問userid
屬性,因此您的json響應: [{'userid':'1'}]
為數組形式,因此您需要使用以下語法: alert(userId[0].userid)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.