Reputation:
I'm developing a script but I mustn't use jQuery library so I need the equivalent of .load() in JS.
I need to do this without jQuery:
$(document).ready(function(){
$('#a').click(function(){
$('body').append('<div id="b"></div>')
$('#b').load('x.html')
});
});
Thanks!
Upvotes: 19
Views: 33194
Reputation: 330
function load(url, element)
{
fetch(url).then(res => {
element.innerHTML = res;
});
}
function load(url, element)
{
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
load("x.html", document.getElementById("b"));
This will load "x.html" and put it inside the element.
Upvotes: 3
Reputation: 6278
function load(url, element)
{
fetch(url).then(res => {
element.innerHTML = res;
});
}
function load(url, element)
{
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
load("x.html", document.getElementById("b"));
Upvotes: 18
Reputation: 31
I found that jquery load run scripts from loaded file, which setting innerHTML to something doesn't do the trick... don't test if you can call an init() function afterwards...
Upvotes: 0
Reputation: 4332
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
/* If you wanted post too */
// xmlhttp.open("POST", "/posturl", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// xmlhttp.send("email=" + "value" + "&message=" + "value" + "&name=" + name"value");
xmlhttp.open("GET", "file_to_get.xml", true/* async, setting to false will block other scripts */);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.alert(xmlhttp.responseText);
}
}
Upvotes: 0
Reputation:
The simple answer is you're doing things that are fairly complicated to get done correctly without a library like jQuery. Here's something that "works", but with no error checking or cross-browser perfection. You really probably don't want this... but here it is.
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('a').addEventListener('click', function (e) {
e.preventDefault();
var div = document.createElement('div');
div.id = 'b';
document.body.appendChild(div);
var xhr = new XMLHttpRequest();
xhr.onload = function () {
div.innerHTML = this.response;
};
xhr.open('GET', 'x.html', true);
xhr.send();
}, false);
}, false);
</script>
</head>
<body>
<a id="a" href="#">load</a>
</body>
</html>
Upvotes: 8
Reputation: 392
If you want to do it without JS, I think this will help you, add this inside #b
<iframe src="x.html"></iframe>
Upvotes: 3