2016-04-21 73 views
0

當我運行以下javascript/php時,在提醒json對象的'userid'屬性時,我總是收到「undefined」。但是,如果我對json對象進行了字符串化,它將返回「[{'userid':'1'}],這是正確的值。Javascript不會訪問json對象

如果我試圖訪問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); 
+0

你能告訴你的JSON結果? –

+0

JSON是否需要觸發JavaScript處理來更改HTML之類的視圖?當我剛開始玩ajax時,它讓我撓了一下頭,所以這可能是你的問題。看看這個項目:https://github.com/ajax-proofs/proofs –

+0

你應該做這樣的事情,而「($行= $結果 - 」num_rows)「處理更少也。 –

回答

1

您不能訪問userid PR因爲你的userID變量包含一個數組 - 這就是json響應中的[]括號的含義:[{'userid':'1'}]。嘗試以這種方式訪問​​它:alert(userID[0]["userid"]);

更好的是,不要返回數組,因爲無論如何你都要檢查$rows == 1

0

是,由#Jack說你不能訪問userid財產,你的JSON響應:[{'userid':'1'}]是數組形式,所以你需要去的語法:alert(userId[0].userid)

+0

讓我知道問題是否解決 –