[英]could not read json data using jquery with for loop
我有一个数据对象,里面有一个带有json数据的数据对象。 这是什么样子。 该文件的名称是data.js
var data =
[
{
title: 'this is title one',
commit: 'this is commit'
},
{
title: 'this is title two',
commit: 'this is commit'
},
{
title: 'this is title three',
commit: 'this is commit'
},
{
title: 'this is title four',
commit: 'this is commit'
},
{
title: 'this is title five',
commit: 'this is commit'
},
{
title: 'this is title six',
commit: 'this is commit'
},
{
title: 'this is title seven',
commit: 'this is commit'
}
]
这是我的代码
for (var i = 0; i < data.length; i++) {
$(container).load(view, function () {
console.log(data[i].title);
li.append('<img src="../images/profile.png" alt="Profile photo" />');
li.append('<span class="commit">' + data[i].title + '</span>');
li.append('<p><a href="#" class="comment">' + data.commit + '</a></p>');
li.append('<section class="clear"></section>');
$('#home ul').append(li);
});
}
现在我的控制台中出现此错误
Cannot read property 'title' of undefined
上面的错误在这条线上
li.append('<span class="commit">' + data[i].title + '</span>');
如何解决这个问题?
好吧,data.js并不是真正的json。
首先从load()切换到getJSON()
$.getJSON(view, function(data) { })
接下来删除行
var data =
只包含json内容。 jQuery将为参数数据分配JSON。
您的json数组包含错误。
您可以在此处http://json.parser.online.fr/验证您的json
必须这样:
{
"title": ["this is title one", "this is title two", "this is title three", "this is title four", "this is title five", "this is title six", "this is title seven" ]
,
"commit": [ "this is commit", "this is commit", "this is commit", "this is commit", "this is commit", "this is commit", "this is commit" ]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.