代码之家  ›  专栏  ›  技术社区  ›  Tanzeel

如何使用JavaScript呈现HTML文件

  •  0
  • Tanzeel  · 技术社区  · 5 年前

    我希望home.html加载到 <div id="content"> .

    <div id="topBar"> <a href ="#" onclick="load_home()"> HOME </a> </div>
    <div id ="content"> </div>
    <script>
          function load_home(){
                document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
      }
    </script>
    

    0 回复  |  直到 11 年前
        1
  •  209
  •   Neuron MonoThreaded    6 年前

    我终于找到了我问题的答案。解决办法是

    function load_home() {
         document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
    }
    
        2
  •  62
  •   Aaron Liske    12 年前

    <div id="topBar">
        <a href ="#" id="load_home"> HOME </a>
    </div>
    <div id ="content">        
    </div>
    
    <script>
    $(document).ready( function() {
        $("#load_home").on("click", function() {
            $("#content").load("content.html");
        });
    });
    </script>
    

    对不起的。为单击而不是加载而编辑。

        3
  •  48
  •   Jay Harris    6 年前

    获取API

    function load_home (e) {
        (e || window.event).preventDefault();
    
        fetch("http://www.yoursite.com/home.html" /*, options */)
        .then((response) => response.text())
        .then((html) => {
            document.getElementById("content").innerHTML = html;
        })
        .catch((error) => {
            console.warn(error);
        });
    } 
    

    XHR API

    function load_home (e) {
      (e || window.event).preventDefault();
      var con = document.getElementById('content')
      ,   xhr = new XMLHttpRequest();
    
      xhr.onreadystatechange = function (e) { 
        if (xhr.readyState == 4 && xhr.status == 200) {
          con.innerHTML = xhr.responseText;
        }
      }
    
      xhr.open("GET", "http://www.yoursite.com/home.html", true);
      xhr.setRequestHeader('Content-type', 'text/html');
      xhr.send();
    }
    

    基于您的约束,您应该使用ajax并确保在调用 load_home() 功能

    Reference - davidwalsh

    MDN - Using Fetch

    JSFIDDLE demo

        4
  •  19
  •   Sam Redway    10 年前

    我看到这个,觉得它看起来很不错,所以我做了一些测试。

    这看起来像是一种干净的方法,但在性能方面,与使用jQuery加载函数加载页面或使用XMLHttpRequest的普通javascript方法(两者大致相似)相比,它落后了50%。

    总之,我建议使用jQuery。该语法尽可能容易使用,并且有一个结构良好的回调供您使用。它也比较快。普通的方法可能要快上几毫秒,但语法很混乱。我只会在无法访问jQuery的环境中使用它。

    这是我用来测试的代码——它相当初级,但是经过多次尝试后,时间恢复得非常一致,所以我会说在每种情况下精确到大约+5毫秒。测试是在Chrome中从我自己的家庭服务器运行的:

    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    </head>
    <body>
        <div id="content"></div>
        <script>
            /**
            * Test harness to find out the best method for dynamically loading a
            * html page into your app.
            */
            var test_times  = {};
            var test_page   = 'testpage.htm';
            var content_div = document.getElementById('content');
    
            // TEST 1 = use jQuery to load in testpage.htm and time it.
            /*
            function test_()
            {
                var start = new Date().getTime();
                $(content_div).load(test_page, function() {
                    alert(new Date().getTime() - start);
                });
            }
    
            // 1044
            */
    
            // TEST 2 = use <object> to load in testpage.htm and time it.
            /*
            function test_()
            {
                start = new Date().getTime();
                content_div.innerHTML = '<object type="text/html" data="' + test_page +
                '" onload="alert(new Date().getTime() - start)"></object>'
            }
    
            //1579
            */
    
            // TEST 3 = use httpObject to load in testpage.htm and time it.
           function test_()
           {
               var xmlHttp = new XMLHttpRequest();
    
               xmlHttp.onreadystatechange = function() {
                    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                    {
                       content_div.innerHTML = xmlHttp.responseText;
                       alert(new Date().getTime() - start);
                    }
                };
    
                start = new Date().getTime();
    
                xmlHttp.open("GET", test_page, true); // true for asynchronous
                xmlHttp.send(null);
    
                // 1039
            }
    
            // Main - run tests
            test_();
        </script>
    </body>
    </html>
    
        5
  •  12
  •   droduit Khelben    5 年前

    这种方法利用了诸如 async/await 以及 fetch 应用程序编程接口。它以文本形式下载HTML,然后将其馈送到 innerHTML 你的容器元素。

    /**
      * @param {String} url - address for the HTML to fetch
      * @return {String} the resulting HTML string fragment
      */
    async function fetchHtmlAsText(url) {
        return await (await fetch(url)).text();
    }
    
    // this is your `load_home() function`
    async function loadHome() {
        const contentDiv = document.getElementById("content");
        contentDiv.innerHTML = await fetchHtmlAsText("home.html");
    }
    

    这个 await (await fetch(url)).text() 看起来有点棘手,但很容易解释。它有两个异步步骤,您可以这样重写该函数:

    async function fetchHtmlAsText(url) {
        const response = await fetch(url);
        return await response.text();
    }
    

    fetch API documentation

        6
  •  6
  •   serup    11 年前

    使用时

    $("#content").load("content.html");
    

    然后请记住,您不能在chrome中本地“调试”,因为XMLHttpRequest不能加载——这并不意味着它不工作,它只是意味着您需要在相同的域aka上测试代码。你的服务器

        7
  •  4
  •   Anup    10 年前

    您可以使用jQuery:

    $("#topBar").on("click",function(){
            $("#content").load("content.html");
    });
    
        8
  •  1
  •   Neuron MonoThreaded    6 年前
    $("button").click(function() {
        $("#target_div").load("requesting_page_url.html");
    });
    

    document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
    
        9
  •  1
  •   Kamil Kiełczewski    6 年前

    尝试

    async function load_home(){
      content.innerHTML = await (await fetch('home.html')).text();
    }
    

    async function load_home() {
      let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'
    
      content.innerHTML = await (await fetch(url)).text();
    }
    <div id="topBar"> <a href="#" onclick="load_home()"> HOME </a> </div>
    <div id="content"> </div>
        10
  •  0
  •   Abdullahi    10 年前

    github上有一个插件,可以将内容加载到元素中。这是回购协议

    https://github.com/abdi0987/ViaJS

        11
  •  0
  •   Pierre.Vriens Krzysztof J    6 年前

    当您想要包含header.php或其他页面时,通常需要这样做。

    在Java中,这很简单,特别是当您有HTML页面并且不想使用PHPInclude函数时,但是您应该编写php函数并将其作为Java函数添加到脚本标记中。

    在这种情况下,你应该写它没有函数后面跟着名字而已。脚本覆盖函数单词并启动include header.php

        12
  •  0
  •   Cak Sup    5 年前

    使用这个简单的代码

    <div w3-include-HTML="content.html"></div>
    <script>w3.includeHTML();</script>
    </body>```
    
        13
  •  -3
  •   Rudolf RemÅ¡ík    11 年前

    <!DOCTYPE html>
    <html>
        <head>
          <script type="text/javascript">
            function showHide(switchTextDiv, showHideDiv)
            {
              var std = document.getElementById(switchTextDiv);
              var shd = document.getElementById(showHideDiv);
              if (shd.style.display == "block")
              {
                shd.style.display = "none";
                std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>"; 
              }
              else
              {
                if (shd.innerHTML.length <= 0)
                {
                  shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
                }
                shd.style.display = "block";
                std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
              }
            }
          </script>
        </head>
        <body>
          <a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
            <span style="display: block; background-color: yellow">Show</span>
          </a>
          <div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
        </body>
    </html>
    

    showhide_embedded.html

    <!DOCTYPE html>
    <html>
        <head>
          <script type="text/javascript"> 
            function load()
            {
              var ts = document.getElementById("theString");
              ts.scrollIntoView(true);
            }
          </script>
        </head>
        <body onload="load()">
          <pre>
            some text 1
            some text 2
            some text 3
            some text 4
            some text 5
            <span id="theString" style="background-color: yellow">some text 6 highlight</span>
            some text 7
            some text 8
            some text 9
          </pre>
        </body>
    </html>
    
        14
  •  -5
  •   Jain Abhishek    8 年前

    如果html文件位于本地,则使用iframe而不是标记。标签不能跨浏览器工作,主要用于Flash

    <iframe src="home.html" width="100" height="100"/>