I have a data object and inside that I have data object with json data inside. Here is how is looks like. the name of the file is 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'
}
]
here is my code
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);
});
}
Now I am getting this error in my console
Cannot read property 'title' of undefined
above error is on this line
li.append('<span class="commit">' + data[i].title + '</span>');
how to fix this?
Well, data.js is not really json.
First switch from load() to getJSON()
$.getJSON(view, function(data) { })
next remove the line
var data =
just have the json contents. jQuery will assign JSON to argument data.
Your json array contains errors.
You can validate your json here http://json.parser.online.fr/
Must be so:
{
"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" ]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.