javascript - 无法从 json 对象获取数据

标签 javascript json ajax django

我有这个脚本:

<script type="text/javascript">
        function requestimg(username){
                $.ajax({
                    url: '{% url "image" %}',
                    data: {
                      'username': username
                    },
                    dataType: 'json',
                    success: function (data) {
                        if (data) {
                            //Printing the whole data
                            console.log(data);
                            //Printing to see where I am
                            console.log("Name: ");
                            //Trying to rint the name
                            console.log(data[0].nombre);
                        }else {
                             alert("May Day");
                        }
                    }
                });
        }

我在读取 json 对象中的属性时遇到问题 当我打印数据时,我得到这个:

{
    json: "[
        {
            "model": "polls.imagen",
            "pk": 17,
            "fields": {
                "n…"36",
                "imagen": "polls/static/pictures/dr.jpg"
            }
        }
    ]"
}

当我打印代码中的数据时,我得到:

Uncaught TypeError: Cannot read property 'nombre' of undefined

我尝试像data.nombre那样编写它,但我只是得到undefined

我也尝试过这个 console.log(data[0].fields);data[0].modeldata.model

重要我想澄清一下,我不知道为什么有 2 个 json 对象,我应该只得到一个,即使我尝试放入 [1] 而不是 [0] 我得到同样的错误。

我尝试过之前一些类似问题的答案,但没有帮助。

最佳答案

您将能够访问以下字段

data.json[0].fields

您的网址的响应是一个数组,名为json

另外 data.json 返回一个字符串,因此将其转换为 JSON

data.json = JSON.parse(data.json);

关于javascript - 无法从 json 对象获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45688012/

相关文章:

javascript - 使用 javascript 实现下拉菜单更改时的重绘功能

javascript - 要数组的对象数组

node.js - 在 Express 应用程序中从 JS 文件附加 JSON 文件

python - 如何在 Python 中打印 MongoDB 对象中 Json 内的值

javascript - 如何根据选择其他选择选项来更改选择选项

javascript - jQuery ReplaceWith() 回调函数来更新内容

javascript - 在单个请求中使用 JavaScript 发送多个 AJAX 调用

javascript - 使用箭头键移动元素

javascript - Mongoose:CastError:模型 ""的路径 "_id"处的值 ""转换为 ObjectId 失败

PHP pdo foreach