简体   繁体   中英

Getting undefined when iterating from JSON API results

I'm having problems reading my JSON result from an API.

My data looks like this:

{
    "Data": [
        {
            "Name": "Company1"
        },
        {
            "Name": "Company2"
        }
    ]
}

And I'm reading it like this:

$.get(API_URL + '/dashboard/', function (data) {
    var newHTML = '';

    $.each(data, function (i, val) {
        newHTML +=  data[i].Name;
    });

    $('#dashboard').html(newHTML);

});

data[i] is returning undefined. What am I doing wrong?

This should work for you.

$.get(API_URL + '/dashboard/', function (data) {
    var newHTML = '';

    $.each(data.Data, function (i, val) {
        newHTML +=  val.Name;
    });

    $('#dashboard').html(newHTML);

});

The each function need to parse the data.Data , not just data ...

Sounds like a pun! But should work!

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