views:

53

answers:

4

Is it possible to load an html document using ajax and then perform a jquery selection on the loaded html?

I want to perform a search against a remote search server and then use the results to reformat an existing page.

EDIT: the find function doesnt seem to return results (length is always 0). Here is the sample html

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
    <title></title>
</head>
<body>

    <p>Hello world</p>

    <p>good bye world</p>

</body>
</html>

And here is the jQuery:

$(document).ready(function() {

  $.ajax({
    url: 'content/HTMLPage.htm',
    dataType: 'html',
    success: function(data) {

      alert($(data).find('p').length);

    }
  });
});
A: 

You can, if you can...

You just could use

var result = $(returned_html) ;

within the ajax success handler, and then do result.find('#id_of_anything'). Your ajax call should have a 'dataType' of 'html' here.

Your problem is, "remote search server" invokes a 'remote domain', which will not possible due to ajax same-origin policy.

Kind Regards

--Andy

jAndy
A: 

Is it possible to load an html document using ajax and then perform a jquery selection on the loaded html? - Yes

You can handle events by using live() or delegate()

c0mrade
Note, I'm not loading this into the DOM of the page, so live() and delegate() are not relevant here. Thanks.
James Westgate
A: 

You can use something like this:

$.get(url, fuction(data) {

  $(data).find();

} );

You basically wrap the returned html content in an jQuery object. Then you can use jQuery selectors with it.

kgiannakakis
A: 

I really struggled with this. I have managed to load a whole document and select from it correctly, but this one had a doctype.

Otherwise it seems it is possible but it has its caveats. The items you are selecting need to have at least a parent node. I dont really think I can mark anything off here as an answer just yet.

This html returned 2 elements:

<div>
  <p>Hello world</p>

  <p>good bye world</p>
</div>
James Westgate