views:

225

answers:

2

When the user clicks a sorting link on my blog, I want to use AJAX to both pull in new posts and update the sorting link section. This would be easy using RJS, but I want to keep my JS unobtrusive and respond to AJAX requests with only data (and no code).

Here's what I'm doing now:

  $('a.order_by').livequery('click', function() {
    $.get(this.href, null, function(data) {
      // The server returns a blob of HTML with a div#posts
      // and a div#sorting
      $("#posts").partial_html(data, "#posts");
      $("#sorting").partial_html(data, "#sorting");
    });
    return false;
  });

and here's the partial_html() function:

// Stolen from the jQuery source for $.load()
jQuery.fn.partial_html = function(data, selector) {
    $(this).html($("<div/>").append(data.replace(/<script(.|\s)*?\/script>/g, "")).find(selector));
}

Obviously this is a bit disgusting -- what's the right way to do this? (It would be super-easy to use two $.load()'s, but that would require a superfluous HTTP request).

A: 

I would store the data returned in a variable (think caching) using $.load() and then do use jQuery to select the divs from that cache and append it to the DOM using $.html()

roosteronacid
+1  A: 
  $("#posts").html($(data).filter("#posts").html());
  $("#sorting").html($(data).filter("#sorting").html());

Works for me. (Though I'm not sure it's the "right" way to do it).

Horace Loeb