Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

jquery - Get contents of <body> </body> within a string

I want to do the following.

$("a").click(function (event) {

    event.preventDefault();

    $.get($(this).attr("href"), function(data) {

        $("html").html(data);

    });

});

I want the behavior of all hyperlinks to make a ajax calls and retrieve the html.

Unfortunately you cannot simply replace the current html with the html you receive in the ajax response.

How can grab only what is within the <body> </body> tags of the ajax response so that i can replace only the contents of the body in the existing html.

Edit: the <body> opening tag will not always be just <body> it may sometimes have a class e.g.

<body class="class1 class2">

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If I understand you correctly, grab the content between the body tags with a regex.

$.get($(this).attr("href"), function(data) {
    var body=data.replace(/^.*?<body>(.*?)</body>.*?$/s,"$1");
    $("body").html(body);

});

EDIT

Based on your comments below, here's an update to match any body tag, irrespective of its attributes:

$.get($(this).attr("href"), function(data) {
    var body=data.replace(/^.*?<body[^>]*>(.*?)</body>.*?$/i,"$1");
    $("body").html(body);

});

The regex is:

^               match starting at beginning of string

.*?             ignore zero or more characters (non-greedy)

<body[^>]*>     match literal '<body' 
                    followed by zero or more chars other than '>'
                    followed by literal '>'

(               start capture

  .*?           zero or more characters (non-greedy)

)               end capture

</body>        match literal '</body>'

.*?             ignore zero or more characters (non-greedy)

$               to end of string

Add the 'i' switch to match upper and lowercase.

And please ignore my comment regarding the 's' switch, in JavaScript all RegExp are already single-line by default, to match a multiline pattern, you add 'm'. (Damn you Perl, interfering with me when I'm writing about JavaScript! :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...