简体   繁体   中英

Create unordered list from JSON object using JS (jQuery)

I would like to create an unordered list using jQuery .each() for the JSON entry object in the code below

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "http://query.yahooapis.com/v1/public/yql?q=SELECT%20title%2C%20description%2C%20link%2C%20pubDate%0AFROM%20feed(0%2C5)%0AWHERE%20url%3D'http%3A%2F%2Ffeeds.feedburner.com%2FffAggregator'&format=json&diagnostics=true&callback=friendFeed",
        data: { get_param: 'value' },
        success: function (data) {
            var names = data

            $('#results').html(data);
        }
    });
});

I would like to achieve this with JavaScript (jQuery) alone

Set JSONP as data type in your AJAX request and specifiy friendFeed as callback function.

In the success callback function, you can then build the unordered list directly from the JSON data. Just iterate over the object you want to use and append li elements to a ul element. Example:

$.ajax({
    type: "GET",
    url: "http://query.yahooapis.com/v1/public/yql?q=SELECT%20title%2C%20description%2C%20link%2C%20pubDate%0AFROM%20feed(0%2C5)%0AWHERE%20url%3D'http%3A%2F%2Ffeeds.feedburner.com%2FffAggregator'&format=json&diagnostics=true&callback=friendFeed",
    data: { get_param: 'value' },
    jsonpCallback: 'friendFeed',
    dataType: "jsonp",
    success: function (data) {
        var obj = data.query.results.entry,  // get entry object (array) from JSON data
            ul = $("<ul>");                    // create a new ul element
        // iterate over the array and build the list
        for (var i = 0, l = obj.length; i < l; ++i) {
            ul.append("<li><a href='" + obj[i].link.href + "'>" + obj[i].title.content + "</a></li>");
        }
        $("#results").append(ul);    // add the list to the DOM
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM