简体   繁体   English

是否可以使用 JavaScript 导入 HTML?

[英]Is it possible to import HTML using JavaScript?

I have some html pages with the same footer.我有一些具有相同页脚的 html 页面。 With JavaScript and only JavaScript could I import another html page inside it?使用 JavaScript 和只有 JavaScript 我可以在其中导入另一个 html 页面吗?

As above, one method is to use jQuery load.如上所述,一种方法是使用 jQuery 加载。 I happened to be doing the exact same thing now, so will post a quick example.我碰巧现在正在做完全相同的事情,所以将发布一个简单的示例。

Using jQuery:使用 jQuery:

$("#yourDiv").load('readHtmlFromHere.html #readMe');

And your readHtmlFromHere.html page would consist of:您的 readHtmlFromHere.html 页面将包括:

<div><div id="readMe"><p>I'm some text</p></div></div>

Here's how you could use just javascript to add a footer to your page.以下是您如何仅使用 javascript 为您的页面添加页脚的方法。

2022 code, using fetch and insertAdjacentHTML : 2022 代码,使用fetchinsertAdjacentHTML

async function addFooter() {
    const resp = await fetch("footer.htm");
    const html = await resp.text();
    document.body.insertAdjacentHTML("beforeend", html);
}

Original 2011 code, usingXMLHttpRequest and innerHTML :原始 2011 代码,使用XMLHttpRequestinnerHTML

var ajax = new XMLHttpRequest();
ajax.addEventListener("load", function () {
    document.body.innerHTML += ajax.responseText;
}
ajax.open("GET", "footer.htm");
ajax.send();

The 2011 code will still work in all browsers today, but fetch is more intuitive, and allows you to avoid coding an event handler callback. 2011 年的代码今天仍然适用于所有浏览器,但fetch更直观,并且允许您避免编写事件处理程序回调。 insertAdjacentHTML is also available for all browsers, so you could use that or innerHTML with either example. insertAdjacentHTML也可用于所有浏览器,因此您可以在任一示例中使用该或innerHTML Only fetch is new, and won't work in IE without a polyfill .只有fetch是新的,并且在没有polyfill的情况下无法在 IE 中使用。

You can use ajax to return a whole HTML page.您可以使用 ajax 返回整个 HTML 页面。 If you wanted to replace the whole page you could replace the body tag and all it's children currently on the page with the body tag returned from the ajax call.如果您想替换整个页面,您可以使用从 ajax 调用返回的 body 标记替换当前页面上的 body 标记及其所有子项。

If you wanted to just replace a section you'd have to write a server-side script to create that section, then use ajax as above but just replace an element rather than the whole page.如果您只想替换一个部分,则必须编写一个服务器端脚本来创建该部分,然后像上面一样使用 ajax,但只需替换一个元素而不是整个页面。

Along with what @Alex mentioned, jQuery has a method .load() that you can use to fetch a specific portion of a page (See Loading Page Fragments heading on that page) .除了@Alex 提到的, jQuery有一个方法.load() ,您可以使用它来获取页面的特定部分(请参阅 Loading Page Fragments header on that page) You specify the URL you want to retrieve along with a selector (so if you wanted only a specific <DIV> 's contents for instance).您指定要检索的 URL 以及选择器(例如,如果您只想要特定的<DIV>的内容)。

Following this answer example (one of the answer in this question), I made this little reusable function:按照这个答案示例(this question中的答案之一),我制作了这个可重用的小功能:

/**
 * Render the array of html files, to the
 * selected container.
 * @param {*} pages - array of html file names
 * @param {*} container - HTML element name
 */
function render(pages, container) {
    const template = document.createElement("template");
    var ajax = new XMLHttpRequest();

    pages.forEach(element => {
        // this is the route where the files are stored
        ajax.open("GET", `./view/shared/${element}.html`, false);
        ajax.send();
        template.innerHTML += ajax.responseText;
    });

    document.querySelector(container).append(template.content);
}

export { render };

Which you can use in your index.js file, like so:您可以在index.js文件中使用它,如下所示:

import { render } from "./tools/render.js";

var headerContent = ["siteName", "navbar"];

render(headerContent, "header");

This is rendering the html files siteName.html and navbar.html , into the <header> tag in the root index.html file of the site.这会将 html 文件siteName.htmlnavbar.html渲染到站点根index.html文件中的<header>标记中。

NOTE.笔记。 This function works on localhost, but for whatever reason (which I still have to fix; I'll let you know when I do) it does not work correctly when working on GitHub Pages.此功能适用于 localhost,但无论出于何种原因(我仍然需要修复;我会在我这样做时通知您)在 GitHub Pages 上工作时无法正常工作。

You could do a server side include, depending on your webserver.你可以做一个服务器端包含,这取决于你的网络服务器。 but the quickest way would probably be to create a JavaScript file that uses document.write or similar to output the html syntax.但最快的方法可能是创建一个使用 document.write 或类似的 JavaScript 文件来输出 html 语法。 and then just include the created JavaScipt file the normal way.然后以正常方式包含创建的 JavaScipt 文件。 more info at: http://webdesign.about.com/od/ssi/a/aa052002a.htm更多信息请访问: http ://webdesign.about.com/od/ssi/a/aa052002a.htm

你当然可以,但如果你所做的只是模板,我建议你在服务器上这样做。

fetch("MyHTMLFile.html").then((response) => {
  response.text().then((text) => {
    targetHTMLElement.innerHTML = text;
  });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM