$ .ajax () get only body

I have a script like this

<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Testing Ajax</title> <script type="text/javascript" src="jquery.js"></script> </head> <body> <a class="test" href="getthis.php">click here</a> <div class="get"></div> <script type="text/javascript"> $('.test').click(function(event){ event.preventDefault(); var a = $('body'); $.ajax({ url: "/getthis.php", dataType: 'text', success: function(data){ $('.get').append(data.find); } }); }); </script> </body> </html> 

with this script i am trying to get getthis.php content

getthis.php contains only this

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> </head> <body> Olalalalala bebe </body> </html> 

when i do this i get the full html getthis.php result

how can i only get body content? which is just average. "Olalalalala bebe"

Can someone give me an explanation?

Thanks...

+4
source share
6 answers

use http://api.jquery.com/load/ you can load certain fragments of the page

+6
source

Pretty easy. Wrap the inside of the BODY with another layer of DIV:

 $.get(url, {}, function(data){ var data = data.replace('<body', '<body><div id="body"').replace('</body>','</div></body>'); var body = $(data).filter('#body'); //... do what you want with body ... }); 
+5
source

I wonder if this helps:

 $(data).text(); 

This seems to come from the box:

 $.ajax({ url: 'http://stackoverflow.com/questions/3861325/ajax-get-body-only/', success: function (data) { alert($(data).text().replace(/\s+/gm, ' ')); } }); 
+3
source

This should do it:

 $('.get').load('/getthis.php body'); 

Edit: Sorry, I just checked this, and it does not work, using body as a selector that surprises me. If I changed getthis.php to this:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> </head> <body> <div id="test"> Olalalalala bebe </div> </body> </html> 

And name it as follows:

 $('.get').load('/getthis.php #test'); 

I get the result you are looking for. But it seems that body not a valid selector in this case.

+2
source

If not required, you exclude html tags from your getthis.php that will be displayed on the page.

0
source
 $.ajax({ url: "some.html", type: "get", dataType: 'html', success: function(data) { $('#here').html(data); $('#here').children('meta,link,title,style').remove(); }, }); 
0
source

All Articles