tags:

views:

128

answers:

9

With $.ajax, I'm getting a JSON response like follows:

[{"project":{"name":"P1111", description":"I like chicken soup","active":true}} .....repeats several times]

What I'd like to do with jQuery is take that JSON response, and loop through it to create the following on id=target

<ul id="target">
  <li>P1111 - I like chicken soup - active</li>
  <li>3311 - I like green soup - active</li>
  <li>4324234 - I like orange soup - active</li>
  <li>123123 - I like hands - active</li>
</ul>

My JSON response from the server:

[{"project":{"name":"3rd project  XXXX","created_at":"2010-09-21T05:00:28Z","updated_at":"2010-09-21T05:00:28Z","site_id":1,"creator":1,"id":3,"description":"I eat chicken","active":true}},{"project":{"name":"It's 10:11pm2","created_at":"2010-09-21T05:11:25Z","updated_at":"2010-09-21T05:22:07Z","site_id":1,"creator":1,"id":7,"description":"It's 10:11pmIt's 10:11pm22","active":true}},{"project":{"name":"My first project","created_at":"2010-09-21T04:15:54Z","updated_at":"2010-09-21T04:15:54Z","site_id":1,"creator":1,"id":1,"description":"Wowwww","active":true}},{"project":{"name":"What a great project","created_at":"2010-09-21T04:16:07Z","updated_at":"2010-09-21T04:58:24Z","site_id":1,"creator":1,"id":2,"description":"Updated Description2","active":true}},{"project":{"name":"the big 6","created_at":"2010-09-21T05:08:22Z","updated_at":"2010-09-21T05:08:22Z","site_id":1,"creator":1,"id":6,"description":"the big 6the big 6","active":true}}]
+1  A: 

Check out jQuery.each which is a sort of foreach statement. With that you can iterate over your JSON object (any JSON object is actually just a pure JavaScript variable, and in your case it's an array of objects).

Emil Vikström
+5  A: 

Using $.ajax

$.ajax({
 url: url,
 dataType: 'json',
 success: function(data) {
    $.each(data, function(i,item){
      $('#target').add('<li>' + item.project.name + '</li>');
    });
 }

});

I suggest using $.getJSON because your code will be shorter, making your transmission to the client smaller.

Thats a rough idea of how to do this. There are many ways of attaching a li to the list.

Shawn Mclean
nice and clean, love that. I just tried that and got an error in Firebug "a is undefined[Break On This Error] a))();else c.error("Invalid JSON: "+a)...f(d)if(i)for(f in a){if(b.apply(a[f], " But I did check JSONLint and it validated my JSON...
WozPoz
i edited how you access the json data. Its `item.project.name`
Shawn Mclean
Just added the JSON above to help clear it up.... not sure yet why it's breaking
WozPoz
thanks, that still errors though...
WozPoz
does it get executed though, and the list gets displayed?
Shawn Mclean
no it doesn't execute, i tried adding an alert in the EACH with the item.project.name and it errors, same error. Does the JSON look ok to you?
WozPoz
Maybe it's the data.items, I tried alerting that after success and it says undefined.
WozPoz
`data` will be the array itself or the complete json response. So there is no data.items. There is `data[0].project.name`
Shawn Mclean
+1  A: 
$.each(data.project, function(i, item) {
     $('#target').append('<li>'+item.name+' - '+item.description+' - '+item.active+'</li>');
});
Mike
This will be slow becouse browser will reflow on every item in the array and also data is an array of objects with `project` field, not object with field `project` which is an array of objects.
jcubic
+1  A: 

Just loop over every item using getJSON:

$.getJSON(url, function(data){
    $.each(data, function(i, item){
        var text = item.project.name + ' - ' 
                 + item.project.description + ' - ' 
                 + (item.project.active ? 'active' : 'inactive');
        $('li').html(text).appendTo($('#target'));
    });
});
Harmen
+1  A: 

Try this

  $.ajax({
    ...
    success: function(data) {
      var lis = $.map(data, function(elem, i) {
         var project = elem['project'];
         return '<li>' + project['name'] + ' - ' + project['description'] + ' - ' +
                (project['active'] ? 'true' : 'false') + '</li>';
      });
      $('#target').append(lis.join('\n'));
    }
  });
jcubic
A: 
var _li="";
jQuery.ajax({
 url:'ur_url',
 type:'Get', //or post or jsonp as per need
 success:function(data)
   {
    jQuery.each(data,function(i,item){
       _li=_li+"<li>"+item.project.name +"  -  " +item.project.description +"  -  " +item.project.active+"</li>";
                                   });
   jQuery('#target').html(_li);
   } 
})
Praveen Prasad
A: 

Try:

var json = [ {"project":{"name":"P1111", "description":"I like chicken soup","active":true}},
                {"project":{"name":"P2222", "description":"I like chicken soup","active":true}} ];
var html = ['<ul id="target">'];
$.each( json, function(i, p) {
        var a = p.project.active ? "active" : "not active";
        html.push("<li>" + p.project.name + " - " + p.project.description + " - " + a + "</li>");
});
$("body").append(html.join(""));
erickb
A: 

I did this to populate a select (id 'schedule'), that's almost the same scenario you are up to.

$.getJSON("../schedule/" + id, function(data) { $.each(data, function(index, value) { $("").attr("value", value.id).html(value.name).appendTo("#schedule"); }); });

Sigmund Lundgren
A: 

I always like to use straight Javascript and put it out to the html document:

document.writeln("<ul id='target'>");
for (project in projects ) {
  var active = (project.active) ? "active" : "NOT active";
  document.writeln('<li>'+project.name+' - '+
                          project.description+' - '+active+'</li>');
}
document.writeln("</ul>");

Or put it all in a string var and then write it to a div:

var htmlStr = "<ul id='target'>";
for (project in projects) {
  var active = (project.active) ? "active" : "NOT active";
  htmlStr += "<li>"+project.name+" - "+project.description+" - "+active+"</li>";
}
htmlStr += "</ul>";
document.getElementById("divTarget").html = htmlStr;
webhead