Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
129 views
Welcome To Ask or Share your Answers For Others

1 Answer

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(/^[sS]*<body.*?>|</body>[sS]*$/ig, '') + '</div>';
var $body = $(body);

now things work as expected.. for example

$body.find('#a')

Hope that helps..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...