Reputation: 611
I'm trying to fetch the last 3 blog posts with the draft = false for my system via jQuery json and following some tutorials if found online but without luck, and with the following keys:
"slug"
"updated"
"title"
"content"
"draft = false"
Here is the json output
{
"posts":[
{
"Blog":{
"id":"1252",
"client_id":"1432",
"slug":"my-blog-slug",
"last_updated_by":"614",
"draft":false,
"created":"2014-09-17 11:18:39",
"updated":"2014-09-17 11:18:39",
"locale":"isl",
"title":"This is the blog title",
"content":"<p>My excellent content.<\/p>",
"author":"John Doe"
},
"UpdatedBy":{
"id":"614",
"name":"John Doe"
}
}
]
}
My current script is below, but i'm pretty sure that i'm doing a lot of things wrong.
<script>
$(document).ready(function() {
$.ajax({
url: "blogs.json",
dataType: "text",
success: function(data) {
var json = $.parseJSON(data);
$('#results').html('Title: ' + json.created + '<br />Description: ' + json.content);
}
});
});
</script>
<div id="results"></div>
Any help would be so much appreciated.
Upvotes: 0
Views: 77
Reputation: 930
try this way:
JS
$(document).ready(function() {
$.ajax({
url: "blogs.json",
dataType: "json",
success: function(data) {
var json = $.parseJSON(data);
$.each(json.posts, function(){
$('#results').html('Title: ' + this.Blog.title + '<br />Description: ' + this.Blog.content);
});
}
});
});
Upvotes: 2
Reputation: 28513
Try this : posts is first key in json object and there could be multiple so access it using index, here it is zero. after getting posts, access each element by its key.
var blog = json.posts[0]["Blog"];
$('#results').html('Title: ' + blog["created"] + '<br />Description: ' + blog["content"]);
EDIT - as per OP comment, adding below code
$(document).ready( function() {
$.parseJSON("/blogs.json", function(data){
var json = $.parseJSON(data);
var blog = json.posts[0]["Blog"];
$.each(blog, function(){
$("div#posts").append("<h1>Title: "+blog['title']+"</h1> <div class=\"post\">Content: "+blog['content']+"</div> <br />");
});
});
Upvotes: 0