jQuery获取json值

时间:2014-09-23 11:13:12

标签: jquery json

我试图通过jQuery json获取我的系统的最后 3篇博文帖子与草案= false ,如果在网上找到了一些教程,但没有运气,并且使用以下密钥:

"蛞蝓"
"更新"
"标题"
"内容"
" draft = false"

这是json输出

{  
  "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"
         }
      }
   ]
}

我目前的剧本如下,但我很确定我做了很多错事。

<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>

任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:2)

尝试这种方式:

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);
            });
        }
    });
});

<强> Demo

答案 1 :(得分:0)

试试这个:posts是json对象中的第一个键,并且可能有多个使用index访问它,这里它是零。获取帖子后,按键访问每个元素。

 var blog = json.posts[0]["Blog"];

 $('#results').html('Title: ' + blog["created"] + '<br />Description: ' + blog["content"]);

编辑 - 根据OP评论,添加以下代码

$(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 />"); 
    }); 
 });

<强> Demo