-3

I'm makin an AJAX request like this:

$.ajax({
    url: baseurl,
    dataType: 'json',
    data: {
        "id": id
    },
    type: "POST",
    success: function(data) {
        console.log(data)
    }
});

The variable data appears in console as:

Object {ids: Array[2], values: Array[2], name: "Test"…}

Expanding it gives:

ids: Array[2]
  0: "1417509840"
  1: "1419964200"
  length: 2

I'm unable to access the ids array. I can access the name variable by data.name, but I cannot access the array elements.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
u134211
  • 315
  • 1
  • 2
  • 8

1 Answers1

2

By the time you see it as data, it's not JSON anymore. It's just an object.

To access the ids array, use data.ids:

console.log(data.ids.length); // 2

Or loop through them:

data.ids.forEach(function(id) {
    console.log("id = " + id);
});

(More about looping through arrays in this answer, which also explains about polyfilling forEach on really old browsers.)

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875