在 JSON 調用中獲取 UNDEFINED

辭典

在 [ajax/json 教程] 中,我只有一個錯誤。我一遍又一遍地遵循教程,但是在輸出“名稱”的對象值時,我的輸出一直得到一個“未定義”。我可以讓它輸出“Rick”的唯一方法是使用 console.log(user[0].name) 而不是教程中的“console.log(user.name)”。按照指示,var 用戶是 JSON.parse。

JSON 文件(user.json):

[
    {
        "id": 1,
        "name": "Rick",
        "email": "[email protected]"
    }
]

HTML 文件 (ajax2.html):

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Ajax 2 - Local JSON</title>
    <style>
        *, html { background: #333; color: #eee; }
    </style>
</head>
<body>
    <button id="button1">Get User</button>
    <button id="button2">Get Users</button>
    <br /><br />
    <h1><div id="user"></div></h1>
    <br />
    <h2><div id="users"></div></h2>

    <script>
        function loadUser() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'user.json', true);

            xhr.onload = function() {
                if(this.status == 200) {
                    var user = JSON.parse(this.responseText);
                    console.log(user.name); // Output name "Rick"
                }
            }

            xhr.send();
        }

        document.getElementById('button1').addEventListener('click', loadUser);


    </script>

</body>
</html>

我不斷收到未定義的。但是編碼:

if(this.status == 200) {
    console.log(this.responseText); // Output the object key/values
}

將正確輸出對象。

關於為什麼我會得到未定義的任何想法?我正在使用 XAMPP,我的 Chrome 瀏覽器也是最新的。

讓我知道是否需要添加任何信息。我已經尋找可能的答案,但它只是把我帶進了一個兔子洞。

梅巴巴

您應該從 user.json 文件中刪除括號。

{
    "id": 1,
    "name": "Rick",
    "email": "[email protected]"
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章