views:

406

answers:

4

I want to make an AJAX call to an HTML-returning page, extract part of the HTML (using jQuery selectors), and then use that part in my jQuery-based JavaScript.

The AJAX retrieval is pretty simple. This gives me the entire HTML document in the "data" parameter of the callback function.

What I don't understand is how to handle that data in a useful way. I'd like to wrap it in a new jQuery object and then use a selector (via find() I believe) to get just the part I want. Once I have that I'll be passing it off to another JavaScript object for insertion into my document. (This delegation is why I'm not using jQuery.load() in the first place).

The get() examples I see all seem to be variations on this:

$('.result').html(data);

...which, if I understand it correctly, inserts the entire returned document into the selected element. Not only is that suspicious (doesn't this insert the <head> etc?) but it's too coarse for what I want.

Suggestions on alternate ways to do this are most welcome.

A: 

You can use load on a new element, and pass that to a function:

function handle(element){
  $(element).appendTo('body');
}

$(function(){
  var div = $('<div/>');
  div.load('/help a', function(){handle(div);});
});

Example: http://jsbin.com/ubeyu/2

Kobi
A: 

You could create a div and then put the HTML in that, like this...

var div=$("<div>").html(data);

...and then filter the data like this...

var thingIWant=$("#content", div.get(0));

...and then use that.

icktoofay
+4  A: 

You can use your standard selector syntax, and pass in the data as the context for the selector. The second parameter, data in this case, is our context.

$.post("getstuff.php", function(data){
  var mainDiv = $("#mainDiv", data); // finds <div id='mainDiv'>...</div>
}, "html");

This is equivalent to doing:

$(data).find("#mainDiv");

Depending on how you're planning on using this, $.load() may be a better route to take, as it allows both a URL and a selector to filter the resulting data, which is passed directly into the element the method was called on:

$("#mylocaldiv").load("getstuff.php #mainDiv");

This would load the contents of <div id='mainDiv'>...</div> in getstuff.php into our local page element <div id='mylocaldiv'>...</div>.

Jonathan Sampson
I would love to use load to hit both the URL and the selector simultaneously, but the insertion into the main document precludes this. I'm hoping the jQuery team will expose the former functionality in a future release!
Craig Walker
A: 

You may want to look at the dataFilter() parameter of the ajax method. It lets you do operations on the results before they are passed out.

jQuery.ajax

Peter Loron