如何使用JavaScript在<div>中加载HTML页面?

Gil*_*eed 143 html javascript google-chrome

我想要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>
Run Code Online (Sandbox Code Playgroud)

当我使用Firefox时,这很好用.当我使用谷歌浏览器时,它会要求提供插件.如何让它在Google Chrome中运行?

Gil*_*eed 205

我终于找到了问题的答案.解决方案是

function load_home() {
     document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一种缓慢且不安全的攻击 - 请参阅下面的答案(太长而无法发表评论) (3认同)
  • 谢谢!远远优于通过ajax这样做 (2认同)
  • 即使这是优雅和干净的,我想如果你真的通过DOM api创建了对象元素会更好. (2认同)
  • 虽然这可能不安全,但如果你正在做一个简单的“桌面文件夹中的本地”开发,这很好——不是每个人都在运行一个银行网站,客户处理银行帐户信息并遇到 XSS 攻击。感谢您的解决方案,根据我的需要,我最终不得不走另一条路线并需要一个 python 服务器并使用常规的 Jquery load() 函数来处理外部动态加载的 html。但这有助于让我解决我的问题 (2认同)
  • @KamilKiełczewski `type="type/html"` 更改为 `type="text/html"` (2认同)

Aar*_*ske 62

您可以使用jQuery加载函数:

<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>
Run Code Online (Sandbox Code Playgroud)

抱歉.编辑单击而不是加载.


Jay*_*ris 47

获取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);
    });
} 
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

根据您的约束,您应该使用ajax并确保在调用该load_home()函数的标记之前加载了您的javascript

参考 - davidwalsh

MDN - 使用Fetch

JSFIDDLE演示


Sam*_*way 18

我看到了这个,觉得它看起来很不错所以我对它进行了一些测试.

这似乎是一种干净的方法,但就性能而言,与使用jQuery加载函数加载页面或使用XMLHttpRequest的大致相似的vanilla javascript方法所花费的时间相比,它滞后了50%.

我想这是因为它在引擎盖下以完全相同的方式获取页面,但它也必须处理构建一个全新的HTMLElement对象.

总之,我建议使用jQuery.语法尽可能简单易用,并且具有结构良好的回调供您使用.它也相对较快.vanilla方法可能会在几毫秒内变得更快,但语法却令人困惑.我只会在我无法访问jQuery的环境中使用它.

这是我用来测试的代码 - 它相当简陋,但是在多次尝试中时间回来非常一致所以我会说精确到大约+ - 5ms.测试是从我自己的家庭服务器在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>
Run Code Online (Sandbox Code Playgroud)

  • https://www.ncsu.edu/labwrite/Experimental%20Design/accuracyprecision.htm (5认同)

Luc*_*iva 9

以现代Javascript方式获取HTML

这种方法利用了现代的Javascript功能async/awaitfetchAPI.它将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 loadHome() {
    const contentDiv = document.getElementById("content");
    contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
Run Code Online (Sandbox Code Playgroud)

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

async function fetchHtmlAsText(url) {
    const response = await fetch(url);
    return await response.text();
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅fetch API文档.


Kam*_*ski 6

尝试

async function load_home(){
  content.innerHTML = await (await fetch('home.html')).text();
}
Run Code Online (Sandbox Code Playgroud)

async function load_home(){
  content.innerHTML = await (await fetch('home.html')).text();
}
Run Code Online (Sandbox Code Playgroud)
async function load_home() {
  let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'

  content.innerHTML = await (await fetch(url)).text();
}
Run Code Online (Sandbox Code Playgroud)


小智 5

使用时

$("#content").load("content.html");
Run Code Online (Sandbox Code Playgroud)

然后记住你不能在本地chrome中"调试",因为XMLHttpRequest无法加载 - 这并不意味着它不起作用,它只是意味着你需要在同一个域上测试你的代码.你的服务器

  • "jQuery"!="javascript"|| jQuery <javascript || OP.indexOf("jQuery")<1 (4认同)

Anu*_*nup 5

您可以使用 jQuery :

$("#topBar").on("click",function(){
        $("#content").load("content.html");
});
Run Code Online (Sandbox Code Playgroud)

  • 请解释你的答案。这也看起来像 jQuery,OP 在问题中没有提到。 (4认同)
  • 先生,这里还有一些答案在 jquery 中 (2认同)
  • jQuery 是执行此类 Ajax 调用的相当标准的方法;所以我觉得答案简洁而恰当。 (2认同)