David
David

Reputation: 11

JSON won't render properly

i'm very new to jQuery :

I'm trying to render my JSON from a jQuery.ajax() :

$.each(data, function(key, val){
  $(key + val).insertAfter("#some-div");
});

but all i get is :

1[object Object]
0[object Object]

Firebug says :

[{"slug": ["This field is required"], "title": ["This field is required."]}, {"slug": ["This field is required"], "title": ["This field is required"]}]

What's wrong ?

Upvotes: 0

Views: 115

Answers (1)

Francois Deschenes
Francois Deschenes

Reputation: 24969

You're getting [object Object] because what's in "data" is in fact JSON and not HTML.

From the Firebug output, it looks like the JSON contains a list or error messages. For some reason, the error message is wrapped in square brackets ([]) which turns in into an array.

What you should be doing is something like this:

$.each(data, function(index, value)
{
  $('<li />').text(value.slug[0] + ' ' + value.title[0]).insertAfter('#some-div');
});

Have a look at jQuery.each and JSON for information on jQuery's .each function and the JSON format respectively.

Upvotes: 2

Related Questions