maxfridbe
maxfridbe

Reputation: 5970

JSON result containing only one item

I'm likely missing something with json and javascript.

[{"commentText":"Testing 123","userPosted":"maxfridbe"},
{"commentText":"Testing 23","userPosted":"maxfridbe"}]

Sometimes I get multiple responses which works with this code:

function(data) 
        {
            var sel = this;

            jQuery.each(data,
                function()
                {
                    sel.append("<li>"+ this.userPosted+ "-" + this.commentText + "</li>");
                });          
        };

Sometimes I only get one response which breaks the above code:

[{"commentText":"another test again welcom","userPosted":"maxfridbe"}]

I know this is because the response is being treated differently than a list.

Looking for the answer to this I get a bit of a runaround. Any solution would be greatly appreciated.

Upvotes: 0

Views: 6553

Answers (3)

maxfridbe
maxfridbe

Reputation: 5970

Playing around with CMS's solution made me realize that data was just a string somehow so:

if (!jQuery.isArray(data))  data = eval(data);

worked because then the data was an object. Not sure why when there are multiple results it does an eval for you.

Upvotes: 0

Mike
Mike

Reputation: 654

I think you should user some optional parameters in your each() function:

function(data) 
    {
        var sel = this;

        jQuery.each(data,
            function(i, item)
            {
                sel.append("<li>"+ item.userPosted+ "-" + item.commentText + "</li>");
            });          
    };

using THIS keyword creates confusion in your case

Hope this helps

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827256

In the second example you provide, it seems to be an array with only one item, if it's like that, it should work, but I think that you're getting only a single object like:

{"commentText":"another test again welcom","userPosted":"maxfridbe"}

If it's a single object $.each iterates over the object properties.

You could check if your data variable is not an array using $.isArray, and if is not, you can wrap it into a single element array, so the $.each function will still work as expected:

//..
if (!jQuery.isArray(data))  data = [data]; // if isn't an array, wrap it

jQuery.each(data, function() {
  sel.append("<li>"+ this.userPosted+ "-" + this.commentText + "</li>");
});
//..

Upvotes: 7

Related Questions