Perform jQuery selection on ajaxed html content
Is it possible to load an html document using ajax and then perform a jquery selection on the loade开发者_StackOverflow社区d 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">
<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);
}
});
});
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()
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>
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.
You can use something like this:
$.get(url, function(data) {
$(data).find();
} );
You basically wrap the returned html content in an jQuery object. Then you can use jQuery selectors with it.
精彩评论