Refresh two different parts of the page using unobtrusive JS (in Rails w / jQuery)

When a user clicks a sort link on my blog, I want to use AJAX to both submit new posts and update the sort links section. This would be easy to use with RJS, but I want my JS to be unobtrusive and respond to AJAX requests with data only (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 function partial_html()

:

// 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 little disgusting - what's the correct way to do this? (It would be very easy to use two $.load()

, but it would require an extra HTTP request.)

0


a source to share


3 answers


  $("#posts").html($(data).filter("#posts").html());
  $("#sorting").html($(data).filter("#sorting").html());

      



Works for me. (Though I'm not sure if this is the "correct" way to do it).

+1


a source


I would store the data returned in a variable (think caching) using $.load()

and then use jQuery to select a div from that cache and add it to the DOM using$.html()



0


a source


I think it might have something to do with my Rails question : not ember, not JS answers, but something in between that I just posted. Let's see if we can find the right solution.

0


a source







All Articles