Since you do not always have control over ids on other pages, it might be interesting for you to use $.get
.
So, you can work with the answer. You can create a DOM with the answer using DOMParser and access the body using elementoDOM.body
, or any element without having to depend on it having an id or a selector.
Let's see a test, putting the body
of the answer in div
whose id is resultado
:
var url = 'https://www.w3.org/TR/xhtml1/';
$.get(url, function(data) {
DOMparser = new DOMParser();
DOMdata = DOMparser.parseFromString(data, 'text/html');
var bodyHTML = DOMdata.body;
/*En el caso de elementos como body deberás usar replace, para que no lo duplique*/
// $('body').replaceWith(bodyHTML);
$('#resultado').html(bodyHTML);
console.log(bodyHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resultado"></div>
Now an example using $.ajax
:
/*Usando $.ajax*/
var url = 'https://developer.mozilla.org/es/docs/Web/HTML';
var request = $.ajax({
url: url,
method: "GET",
dataType: "html"
});
request.done(function(data) {
DOMparser = new DOMParser();
DOMdata = DOMparser.parseFromString(data, "text/html");
var bodyHTML = DOMdata.body;
$('#resultado').html(bodyHTML);
});
request.fail(function(jqXHR, textStatus) {
alert("Error : " + textStatus);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resultado"></div>
NOTE:
In the specific case of body
, if you do this:
$("body").html(bodyHTML);
will double the body
.
You should use in that case:
$("body").replaceWith(bodyHTML);