I load a html with ajax. I want to load the result in a jquery object. I tried that but it returns null. How can I do this? I got a complete page including doctype, head elements and body elements.
var test = $(result); //result contains html code
alert(test.html()); //returns null
I load the data with this function.
function ajaxLoadContent(element) {
$.ajax({
url: "url to the page",
type: "GET",
timeout: 5000,
datattype: "html",
success: function(result) {
//handler
},
});
return false;
It's a while ago, but maybe you're still interested in it..
The intern implementation of $(String)
is not able to build an jQuery object that contains head
or body
tags. It will simply ignore them and move all elements inside on level up.
So if your string is for example
<html>
<head>
<meta ...>
</head>
<body>
<div id="a"/>
</body>
</html>
the resulting jQuery object will be an array of two elements
[<meta ...>, <div id="a" />]
to get a body
-like jQuery object cut everything but the body content before passing it to jQuery:
body = '<div id="body-mock">' + html.replace(/^[\s\S]*<body.*?>|<\/body>[\s\S]*$/ig, '') + '</div>';
var $body = $(body);
now things work as expected.. for example
$body.find('#a')
Hope that helps..
test is just an html string, so you could simply do this to show the contents
alert(result);
and if you want to bind that to an element
$("#myDiv").html(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With