F.Kraemer F.Kraemer - 26 days ago 4
JSON Question

Json object to varible to html with jquery

So i have this code and i dont get it to work, im working on a jquery based blog with JSON loaded objects and I have hit a wall. I need the objects properties into to a div element in my body to make blog-posts. I should be able to just put a new post in the JSON file and it should appear in the body. I have no clue on how to do this, my code looks like this so far:

$( document ).ready(function() {

$.ajax({
dataType: "json",
url: "posts.json",
}).done(function(resp){

for(var p in resp){
if(resp.hasOwnProperty(p)) continue;
var title = resp[p].title;
var content = resp[p].content;
var author = resp[p].author;
var date = resp[p].date;
var image = resp[p].image;


}

});

});


and the JSON file:

{
"post1" : {
"title": "My day",
"content" : "blalbvblblblblblblallksdlmalmdksdkasd",
"date" : "12/0-16",
"author" : "robert",
"image" : "../blogg/img.jpg"
},
"post2" : {
"title": "This right here",
"content" : "blalbvblblblblblblallksdlmalmdksdkasd",
"date" : "12/0-16",
"author" : "robert",
"image" : "../blogg/img.jpg"
},
"post4" : {
"title": "Min vackra",
"content" : "blalbvblblblblblblallksdlmalmdksdkasd",
"date" : "12/0-16",
"author" : "klara",
"image" : "../blogg/img.jpg"
}

}


First of all the varibles i have created is undefined, why?

How do i make the varibles to contain diffrent posts?

Sorry that i suck on programming...

Answer

Use object-keys pattern like this:

for (var key in object) {
    if (!object.hasOwnProperty(key))
        continue;
    var element = object[key];
    console.log(element);
}

You can add elements in dom use jquery append.

example