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).