【问题标题】:how to add html file to html file without jquery如何在没有jquery的情况下将html文件添加到html文件
【发布时间】:2020-05-16 07:29:36
【问题描述】:

当在我的网站上单击一个 div 时,我希望将另一个 html 文件的内容添加到现有的 html 中。我尝试了很多方法,但找不到解决方案。我不想使用 iframe 或 object 或 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?

我还将使用 websockets,所以我怀疑这会改变答案。

【问题讨论】:

    标签: html file load add


    【解决方案1】:

    您可以使用带有 javascript 的 XMLHttpRequest 来加载 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); 
    
    }
    

    【讨论】:

    • 是否可以使用 web sockets 做一个版本?我使用的是 websockets 而不是 https
    • 不是我的,我不熟悉 websockets。但是我不得不使用它一次,我的代码灵感来自这个,希望它可以帮助你:github.com/zhenbianshu/websocket
    猜你喜欢
    • 2022-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多