如何将html文件添加到没有jquery的html文件中

问题描述 投票:0回答:1

当在我的网站上单击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进行此操作?

html file load add
1个回答
0
投票

您只可以将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); 

}
© www.soinside.com 2019 - 2024. All rights reserved.