开发者

Doing a .post on multiple objects in Jquery on ready

开发者 https://www.devze.com 2022-12-20 18:34 出处:网络
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:

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?


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);
    });
  });

});


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'));
});
0

精彩评论

暂无评论...
验证码 换一张
取 消