我有这个脚本:
<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].model
、data.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/