Query HTML returned from AJAX
How can I quer开发者_开发知识库y HTML thats returned from AJAX?
I tried
$.post("gethtml.php", { url: $url.val() }, function(data) {
var $html = $(data),
$links = $("link, script, style", $html),
$body = $("body", $html);
$links.each(function() { $(this).addClass("tmp"); });
console.log($html);
console.log($body.html());
});
$html
looks like [meta, title, script, style#gstyle, script, textarea#csi, div#mngb, iframe, center, script, script]
and $body.html()
null
UPDATE
A simple setup at http://jsfiddle.net/uvnrJ/1/
$(function() {
var html = "<!doctype html><html><head><title>title here ... </title></head><body>This is the body</body></html>",
$html = $(html);
console.log($html); // jQuery(title, <TextNode textContent="This is the body">)
console.log($html.find("body")); // jQuery()
console.log($html.find("title")); // jQuery()
console.log($html.filter("title")); // jQuery(title)
});
Shows that jQuery seem to have problems parsing the HTML string?
Try this...
..........
var elements = $('<div></div>');
elements.html(data);
alert(elements.find('body').html());
...........
I think you should search for your elements directly in the data
variable or use the find()
method on $(data)
. Something like:
$.post("gethtml.php", { url: $url.val() }, function(data) {
var $html = $(data).find('html'), // First way
$links = $("link, script, style", data), // Second way
$body = $("body", data); // Could be better written as $(data).find('body')
$links.each(function() { $(this).addClass("tmp"); });
console.log($html);
console.log($body.html());
});
I ran into the same issue and was forced to resort to parsing the HTML string directly:
var headStartIndex = htmlString.toLowerCase().indexOf("<head>") + "<head>".length;
var headEndIndex = htmlString.toLowerCase().indexOf("</head>");
var newHead = htmlString.substring(headStartIndex, headEndIndex);
var bodyStartIndex = htmlString.toLowerCase().indexOf("<body>") + "<body>".length;
var bodyEndIndex = htmlString.toLowerCase().indexOf("</body>");
var newBody = htmlString.substring(bodyStartIndex, bodyEndIndex);
console.log(newHead);
console.log(newBody);
you can try this, This works
$.ajax({
'url': url,
'dataType': 'html',
'success': function(e){
var $div = $("<div id='_some_id'>" + e + "</div>");
$div = $div.filter("_some_id");
$div.find("span"); // you can search for anything here. it would work now
}
});
精彩评论