如何将json格式的数组数据从jquery返回到html

How to return json formated array data from jquery to html

本文关键字:jquery 返回 html 数据 数组 json 格式      更新时间:2023-09-26

从FB获取数据的示例。。。

$(document).ready(function(){
    var name;
    var link;
    var gender;
    var id;
    $.getJSON( "http://graph.facebook.com/4/", function( json ) {
        name = json.name;
        link = json.link;
        gender = json.gender;
        id = json.id;
        var person = {name:name,link:link,gender:gender,id:id};
        console.log(person); 
        // This gives me exactly what I need but only in console view.
        $('html').text(person); 
        // This just writes [object Object] inside my window
        return person;
    });     
});

我很感激你的帮助,我知道这是最基本的,但现在我的大脑没有正常工作:''

I也建议使用某种模板系统,如下划线、车把、mustasche等。但是,如果使用有限,您可以自己动手,而不是将整个框架用于一个模板。

HTML中需要一些占位符。在这个例子中,我使用了Mustasche.js风格的占位符。示例:

        <html>
        <body>
            <ul>
                <li>name: {{name}}</li>
                <li>gender: {gender}</li>
                <li>link: {{link}}</li>
                <li>id: {{id}}</li>
            </ul>
        </body>
    </html>

然后我们想用适当的值替换占位符,可以这样做:

...
$.getJSON( "http://graph.facebook.com/4/", function( json ) {
    name = json.name;
    link = json.link;
    gender = json.gender;
    id = json.id;
    var person = {name:name,link:link,gender:gender,id:id};

    // Get the current HTML from the selector
    var template = $("html").html();
    // Replace each placeholder w/ the correct thing
    template = template.replace("{{name}}", name);
    template = template.replace("{{link}}", link);
    template = template.replace("{{gender}}", gender);
    template = template.replace("{{id}}", id);
    // Write the new HTML to the selector
    $("html").html(template);
    return person;
});
...

我建议使用类似_.template() 的模板函数

var compiled = _.template("<p>Name: <%= name %></p>");
compiled(person);
//<p>Name: Theresa</p>

http://underscorejs.org/#template