I am trying to load a page’s body just like here: jQuery: Load body of page into variable.
However, in this thread no one provided a working solution because $.load() cuts off the <!DOCTYPE>, <html> and <body> tag by default (afaik). I chose the $.get() method and I already got the page’s entire content as a string, but now I am not able to get just the <body> tag (or rather: what’s inside the <body> tag).
So far I have tried:
$.get(uri, function(data){
console.log(data); // --> the entire page's content is logged
});
$.get(uri, function(data){
console.log($(data)); // --> i guess that's the entire site as an object
});
$.get(uri, function(data){
console.log($(data).find("body")); // --> this should be the <body> tag as an object, but console just outputs "[ ]"
});
Explanation
Hm.. let’s see if I can properly demonstrate this.
$.get()is a shorthand for$.ajax().So when you do this
You’re really doing this
And by default, it returns the page as HTML. Or rather, by default, it first checks the MIME-type on the page, and if none is found, it returns HTML. If you want to tell it what you would like to return, you can either do it in the MIME-type on the server page, or you could use $.getJSON()
If you want the data returned from your request in form of an object, JSON is the way to go.
The only real difference in the code, really, is
replace your
$.get()with$.getJSON()or
add
dataType: "json"in the$.ajax()so it can expect JSON data to be returned from the page.
Now all you need to do is prepare the data on the server side, using
json_encode()This is the way to go if you want objects returned from a request.
Solution
Apart from server-side fix with the
json_encode(), this is the solution.Alternative solution
Assuming you want to keep your
$.get()All you need is the text between
<body>and</body>Here’s an example
And here’s a more advanced answer on that one.