Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

javascript - How to parse a Json list like this and display its elements in HTML?

I got an Json object by using jQuery's getjson() method like that:

<script>

$(document).ready(function(){

  $("button").click(function(){
    $.getJSON(the_api_url, {}, function(data) {
        // do something
    });
  });
  });

});

</script>

The data is an array list, and its format is like this:

[
    {
        id : "001",
        name : "apple",
        class : "fruit",
        colour : "red"
    },
    {
        id : "002",
        name : "melon",
        class : "fruit",
        colour : "green"
    },
    {
        id : "003",
        name : "banana",
        class : "fruit",
        colour : "yellow"
    }
]

I am new to JavaScript and don't know how to parse and display it in html page. Could you guys help me with the code in the '//do something' part?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add a html element like

<ul id="ct"></ul>

then

$(document).ready(function(){

    $("button").click(function(){
        $.getJSON(the_api_url, {}, function(data) {
            var $ul = $('#ul')
            $.each(data, function(idx, item){
                $ul.append('<li style="color: ' + item.color + '">' + item.name + '-' + item['class'] +'</li>')
            })
        });
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...