Does an array returned from an AJAX request from the server (encoded and parsed JSON) have a 'results' property?

StackOverflow https://stackoverflow.com/questions/21999888

Question

I have a function that fetches data from a server via an AJAX request. The asynchronous callback takes the data and then displays it to the DOM.

I'm aware that the getJSON AJAX request is supposed to return an array of strings (and is automatically parsed for my use). So I want to take that array of strings and cycle through them using jQuery's $.each method, which takes 2 arguments - the collection and a function that operates on each item in the collection.

Here's the relevant code:

setInterval(function () {
            $.getJSON("https://api.parse.com/1/classes/chats")
            .done(function(dataReceived){  
                $('.messages li').remove();
                $.each(dataReceived.results, function (index, value) {
                    $('.messages').append('<li>' + value.text + '</li>')
                })    
            });
        }, 2500);

My question is with regards to the array that's returned from the getJSON request - in my function it's a parameter named 'dataReceived'...

That's an array of strings that's already been parsed so it's Javascript ready, right?

Also, and this is the main crux of my question - I wasn't aware that there's a 'results' property on a Javascript array? Or is it only that the getJSON function returns an object/array that has a results property? I'm a little bit lost here...If anyone could clear that up for me (whether by directly answering or with the appropriate documentation) that would be great. Because the code doesn't work if I just pass 'dataReceived' into the $.each-iterator. It requires the 'results' property (dataReceived.results).

Was it helpful?

Solution

I'm aware that the getJSON AJAX request is supposed to return an array of strings (and is automatically parsed for my use).

Not entirely. jQuery.getJSON() will parse a JSON response into the equivalent JavaScript instances and values. But, what those values are depends entirely on the response.

I wasn't aware that there's a 'results' property on a Javascript array?

In this case, since the request is to Parse, their basic query responses follow the format you're finding (amended with comments):

The result value is a JSON object that contains a results field with a JSON array that lists the objects.

{               // root object
  "results": [  // array of results
    {           // individual result object
      // ...
    },
    {           // another result object
      // ...
    }
  ]
}

In the callback, dataReceived will be equal to the "root" Object defined by parsing such JSON data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top