How can i select one object from many objects in a JSON file with this jquery code
I need to get the latest blog post in the top of my page, the main area. All the posts is stored in a JSON file and when i make a new post it should come on top of my webpage to the main area. I also have a menu with all the posts listed. When I click on a "post" it should appear in the main area and when i reload the page again it should show the latest post in the main area. Hoq can i do that with jquery? this is my code so far:
This is the JSON file:
Code:
{
"postHead": {
"title": "My day",
"content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
"date": "12/0-16",
"author": "Me",
"image": "../img/post1.JPG"
},
"post2": {
"title": "This right here",
"content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit ",
"date": "12/0-16",
"author": "Me",
"image": "../img/post2.JPG"
},
"post4": {
"title": "Min vackra",
"content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit ",
"date": "12/0-16",
"author": "Me",
"image": "../img/post3.JPG"
}
}
This is Script file:
Code:
$(document).ready(function() {
$.ajax({
dataType: "json",
url: "posts.json",
}).done(function(object) {
var result = $("#result");
for (var key in object) {
if (!object.hasOwnProperty(key))
continue;
var element = object[key];
result.append(
"<div class='col-sm-12' id='blog-post'>" +
"<div><h2 class='blog-post-head'>" + element.title + "</h2></div>" +
"<div><img src=" + " ' " + element.image + " ' " + "class='img-thumbnail'></div>" +
"<p>" + element.content + "</p>" +
"<div><p><strong>" + element.author + "</strong></p></div>" +
"<div><p><i>" + element.date + "</i></p></div>" +
"</div>")
side.append("<li><a href=" + this + ">" + element.title + "</a></li>");
};
});
});
HTML FILE:
So my problem is that I have no clue on how to do this.
stackoverflow:
javascript - How can i select one object from many objects in a JSON file to show at the top of my website? - Stack Overflow