I am trying to load one or more page from different domain inside div of my page on page load. Each page will be loaded in separate div.
I can do this using jquery but I do not want to do this using javascript so that I do not have to add the jquery script as I am not using jquery in my project anywhere.
Below is the jquery code
$(".Widget").each(function () {
var url = $(this).attr("data-url");
$(this).load(url, function (response, status, xhr) {
if (status == "error") {
alert("There was an error: " + xhr.status + " " + xhr.statusText);
}
});
});
I have the equivalent javascript code
var widgets = document.getElementsByClassName('Widget');
for (var i = 0, len = widgets.length; i < len; i++) {
debugger;
var widget = widgets[i];
var xhr = new XMLHttpRequest();
xhr.onload = function () {
widget.innerHTML = this.response;
};
xhr.open('GET', widget.getAttribute("data-url"), true);
xhr.send();
}
But it is displaying only one page in the last div having class Widget
.
Following code worked for me
I have created a separate function load
function load(url, element) {
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
and called that function inside a for loop
var widgets = document.getElementsByClassName('Widget');
for(var i = 0, len = widgets.length; i < len; i++) {
var widget = widgets[i];
load(widget.getAttribute("data-url"),widget);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.