当在我的网站上单击div时,我希望将另一个html文件的内容添加到现有的html中。我尝试了许多方法,但找不到解决方案。我不想使用iframe或对象或jquery或php。
function loadhtmlfile(filename, filetype, location){
var fileref=document.createElement('link');
fileref.setAttribute("rel", "html");
fileref.setAttribute("type","text/html");
fileref.setAttribute("href", filename);
document.getElementById("parentDiv").appendChild(fileref);
}
loadhtmlfile("my.html", "html", "parentDiv");
这会添加html文件的链接。它不会添加html文件的实际内容。
同样,根据我所读的内容,听起来最好使用服务器应用程序执行此操作。我正在使用node.js。如果最好在服务器端进行操作,如何使用node.js进行此操作?
您只可以将XMLHttpRequest与javascript一起使用以加载HTML内容:
function loadFile(file) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file);
xhr.addEventListener('readystatechange', function() { // load the page asynchronously
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { // if the file is correctly loaded
document.getElementById('yourelement').innerHTML = xhr.responseText;
}
});
xhr.send(null);
}