views:

104

answers:

2

Right now, what i'm trying to do is display some lists on a page and pull out that information from the server using Jquery. The code looks like:

<div class="list" name="category1" />
<div class="list" name="category2" />
<div class="list" name="category3" />

....

$(".list").ready(function(){
  $.post("/getData", "{name=category#}"
    function(data) {
      // Do something here to display the list
    }
  );
});

Assuming that /getData returns the needed ul .... /ul html data, how do I go about replacing the text in the divs with the data sent back? I tried different variations of $this.html(data) with no luck. Also, is there a way to select the name of the div to send back as a .post parameter?

A: 

Try $(div[name=category1]).html(dataFromResponse);

Or, if you'd want the same text in each div: $(div.list).html(dataFromResponse);. This all depends on your context, you could skip div if you don't have any other matching selectors.

Edit based on comment: do you mean something like this?

// fetch new content
function getContentByCategory(name) {
    $.post(
      '/getData',
      {category: name},
      function(response) {  handleResponse(name, response); }
    );
}

// change the looks
function handleResponse(name, response) {
    $('div[name='+name+']').html(response);
}

// trigger it all
$('.list').each(function(){
    getContentByCategoryName($(this).attr('name'));
});
chelmertz
I was hoping on having a dynamic number of lists so I was thinking that hardcoding in div[name=category#] would be a bad idea. I was also hoping to use the category names as a post argument so that the server would return back different lists based on the name.
Matthew
+1  A: 

For starters, you have a few errors in your code. The ready event should be used on the document object, not the list class. Also, you are missing a comma in the $.post call. Here's the corrected code with a dynamic aspect added in. I have not tested it but it should work barring any slight changes that may need to be made.

$(document).ready(function() {

  $('.list').each(function() {
    var list = $(this);
    $.post('/getdata', {category: list.attr('name')}, function(result) {
      list.html(result);
    });
  });

});
ryanulit
Awesome. I had to switch that to .ajax since I wanted to do something in case of errors, but otherwise it worked perfectly! Thanks!
Matthew
No problem. Glad it worked out for you.
ryanulit