开发者

Replacing a HTML tag using JQuery

开发者 https://www.devze.com 2023-01-24 23:03 出处:网络
Ok so after an AJAX Get request \'success\' is called and the string \'data\' is passed, which contains the html of the site requested. Now I want to extract everything in the <body> tag of the

Ok so after an AJAX Get request 'success' is called and the string 'data' is passed, which contains the html of the site requested. Now I want to extract everything in the <body> tag of the current site and repl开发者_如何学JAVAace it with everything in the <body> tag that's stored in the data string. How is this done?

I tried var b = $(data).find('body'); and then .replaceWith(b) but b is apparently an object.

Thanks for your help!

Edit; Ajax:

$.ajax({
        type: "GET",
        url: "managefiles.php",
        dataType: "html",
        success: function(data){
          ...
        }
     });


All that you need to do is replace the html() of the body tag

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

http://api.jquery.com/html/


Append it to body

$("body").empty(); // clear
b.appendTo("body"); // append new
  • jQuery appendTo


$('body').html(data);


This can be a little tricky because browsers behave differently in the situation where you pass an entire HTML document into a jQuery object.

Depending on which browser you're using, some tags (including <body> in some cases) will be stripped away.

While you could just add the entire HTML document to the current <body> and hope that the browser does the right thing, it would be better to have your server return only the content you actually want.


EDIT: If you can't modify the HTML coming from the source, you could try this in order to make it a little safer:

var $data = $(data);
var $contents;

if( $data.filter('body').length ) {
  $contents = $data.filter('body').contents();
} else if( $data.find('body').length ) {
  $contents = $data.find('body').contents();
} else {
  $contents = $data;
}

$(document.body).empty().append( $contents );
0

精彩评论

暂无评论...
验证码 换一张
取 消