How do I load an HTML page in a
using JavaScript?

后端 未结 15 1936
醉话见心
醉话见心 2020-11-22 08:29

I want home.html to load in

15条回答
  • 2020-11-22 08:55

    When using

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

    Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server

    0 讨论(0)
  • 2020-11-22 09:00

    You can use the jQuery :

    $("#topBar").on("click",function(){
            $("#content").load("content.html");
    });
    
    0 讨论(0)
  • 2020-11-22 09:00
    <script>
    var insertHtml = function (selector, argHtml) {
    $(document).ready(function(){
    
        $(selector).load(argHtml);
     
    });
    var targetElem = document.querySelector(selector);
        targetElem.innerHTML = html;
    };
    
    var sliderHtml="snippets/slider.html";//url of slider html
    var items="snippets/menuItems.html";
    insertHtml("#main",sliderHtml);
    insertHtml("#main2",items);
    </script>
    

    this one worked for me when I tried to add a snippet of HTML to my main.html. Please don't forget to add ajax in your code pass class or id as a selector and the link to the HTML snippet as argHtml

    0 讨论(0)
  • 2020-11-22 09:03

    There is this plugin on github that load content into an element. Here is the repo

    https://github.com/abdi0987/ViaJS

    0 讨论(0)
  • 2020-11-22 09:04

    If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash

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

    0 讨论(0)
  • 2020-11-22 09:08

    Fetching HTML the modern Javascript way

    This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.

    /**
      * @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");
    }
    

    The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:

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

    See the fetch API documentation for more details.

    0 讨论(0)
提交回复
热议问题