【发布时间】:2017-08-15 07:10:09
【问题描述】:
我有这个脚本:
<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[1].fields.nombre访问nombre字段(它似乎是数组中的第二项,所以data[1]不是data[0]) -
@donnikitos 我试过了,它说 Uncaught TypeError: Cannot read property 'fields' of undefined
-
@JoseRamon 我刚刚展开了你的回复,试试
data[0].json[0].fields.nombre应该可以这样做 -
@donnikitos Uncaught TypeError: Cannot read property 'json' of undefined,我用
data[0],data[1],data[n].json[n]尝试过
标签: javascript json ajax django