I'm trying to make an automatic news feed on a project website, where all the posts are put into a JSON file and then formatted on the news page accordingly. I've finally figured out how to get the json parser to show SOMETHING but that something is just a bunch of "undefined" bits all over the page. What am I doing wrong?
The jquery/html snippet
<script>
$.getJSON("js/news.json", function (data) {
$.each(data.posts, function (val) {
var title = val.title;
var date = val.date;
var content = val.content;
$("#newscontainer").append('<div><h1>' + title + '</h1><h2>' + date + '</h2><p>' + content + '</p></div>');
});
});
</script>
<div id='newscontainer'>
</div>
The JSON snippet
{
"posts": [
{
"title": "title1",
"date": "8302014",
"content": "LotsoftextLotsoftext"
},
{
"title": "title2",
"date": "8312014",
"content": "CopiousquantitiesoftextCopiousquantitiesoftext"
},
{
"title": "title3",
"date": "8322014",
"content": "onlyalittletext"
}
]
}
val
in your code is the index
, you should use the second argument of the callback.
$.each(data.posts, function (index, val) {
You can also use the this
keyword.
Try this one :
var post_title = val.title;
var post_date = val.date;
var post_content = val.content;
var divTag = document.createElement("div");
newscontainer.appendChild(divTag);
var h1Tag = document.createElement("h1");
h1Tag.innerHTML = post_title;
newscontainer.appendChild(h1);
var h2Tag = document.createElement("h2");
h2Tag.innerHTML = post_date;
newscontainer.appendChild(h2);
var pTag = document.createElement("p");
pTag.innerHTML = post_content;
newscontainer.appendChild(p);
You can use the each() function on your list:
$(data.posts).each(function() {
var $this = this;
$("#newscontainer").append('<div><h1>' + $this.title + '</h1><h2>' + $this.date + '</h2><p>' + $this.content + '</p></div>');
});
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.