简体   繁体   中英

Looping through JSON data using jQuery

I'm trying to get specific information from a JSON file (Squarespace) with the aim of appending it to a <div> . I need to loop through the data and get the location from each post. This is the code I'm using:

$.getJSON("http://www.theluxedit.com/?format=json-pretty", function(data) {
    $.each(data, function(index, value) {
        $('.locationData').append(data.items.location.addressLine2);
    });
});

It will only work if I specifiy the item using an integer, such as:

$('.locationData').append(data.items[1].location.addressLine2);

This seems to be working for other examples I've tried, am I maybe getting the JSON concatenation wrong?

The issue is you need to iterate through the items themselves rather than the entire object returned:

var $locationData = $('.locationData');
$.getJSON("http://www.theluxedit.com/?format=json-pretty", function(data) {
    $.each(data.items, function(index, item) {
        $locationData.append(getLocationEl(item.location.addressLine2));    
    });
});

function getLocationEl(address) {
    return $('<div>', { text: address });
}

By doing this, each iteration will look at a different item. You can then access properties on that item directly, rather than from the top-level data returned.

Also, I am assuming this is being run on theluxedit.com. Otherwise you will get an error. See this for more info: "No 'Access-Control-Allow-Origin' header is present on the requested resource"

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