views:

75

answers:

3

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.

+3  A: 

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>");
});
//..
CMS
This sounds right to me. Maxfriebe should pull out firebug and look very carefully at his data.
timdev
That data was from firebug.
maxfridbe
A: 

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

Mike
A: 

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.

maxfridbe
If your data is just a string, you should use the dataType: 'json' option on your ajax request, or use the getJSON function
CMS