当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Turning JSON data into HTML

问题描述:

I'm trying to display the author of each post

JSON

{

"meta": {

"status": 200,

"msg": "OK"

},

"response": {

"blog": {

"title": "title",

"name": "blog",

"posts": 123,

"url": "blog_url",

"updated": 123456,

"description": "description"

},

"posts": [{

"blog_name": "blog_name",

"author": "author",

"id": 123456,

"post_url": "post_url",

"date": "date",

"timestamp": 123456,

"state": "published",

"format": "html",

"title": "title"

}],

"total_posts": 123

}

}

JAVASCRIPT

$(document).ready(function () {

$.ajax({

type: 'GET',

url: 'something.json',

data: {get_param: 'value'},

dataType: 'jsonp',

success:function(data){

console.log(data);

$.each(data.response.post, function() {

$.each(this.Object, function() {

$('#post').html(this.author);

});

});

}

});

});

网友答案:

There are different ways you can render json data. I prefer to use a template for each item. I find it flexible and easy to maintain. You could also concatenate strings inside a $.each loop. Anyway my version:

success: function (data) {
    var template = $('#post-template').html();
    $.each(data.response.liked_posts, function(i, post) {
        $('#post').append(template.replace(/\{\{(.*?)\}\}/g, function(a, b) {
            return post[b];
        }));
    });
}

Where HTML template is stored in script tag:

<script type="html/template" id="post-template">
    <h3>{{blog_name}}</h3>
    <a href="{{post_url}}">Read</a>
</script>

Demo: http://jsfiddle.net/KBnga/

网友答案:

You have to parse your JSON into JS object. You can do that with jQuery like this..

var likedPosts = $.parseJSON(data.response.liked_posts);
$.each(likedPosts, function() {
    var blog_name = this.blog_name; 
    console.log(blog_name);
});

Also, without knowing what type of element $('#post') is it's hard to tell how you should display it for $('#post'). Assuming $('#post') is a DIV then you could append another HTML element to it to display it.

var likedPosts = $.parseJSON(data.response.liked_posts);
$.each(likedPosts, function() {
      var blog_name = this.blog_name; 
      $('<p>'+blog_name+'</p>').appendTo('#post');
});
网友答案:

Have never used tumblr API but try this way:

$.ajax({
    type: 'GET',
    url: 'http://api.tumblr.com/v2/blog/'+blog+'.tumblr.com/likes?api_key='+api_key+'',
    data: {get_param: 'value'},
    dataType: 'jsonp',
    success:function(data){
        console.log(data);
        $.each(data.response.liked_posts, function(index,value) {
            $('#post').append("<p>"+value.blog_name+"</p>");
        });
    }
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: