How do I append HTML from a document loaded with AJAX?

前端 未结 6 1471
闹比i
闹比i 2021-01-13 19:13

I am trying to append the contents of a .html file to the body of my main page. Basically, I am trying to make a reusable chunk of html that I can load into any page with a

相关标签:
6条回答
  • 2021-01-13 19:32

    Js haven't native method for this task, but you can use jquery method load

    ${element}.load('./template.html');
    

    Or, create element-container, and use innerHTML prop

    request.addEventListener("load", function(event_) {
        //This is the problem line of code
        //How do I get the contents of my response to act like an element? 
        var container = document.createElement("div");
        container.innerHTML = this.responseText;
        document.body.appendChild(container);
    }, false);
    

    UPD
    Convert string to DOM.

    function strToDom(str) {
        var tempEl = document.createElement('div');
        tempEl.innerHTML = str;
        return tempEl.children[0];
    }
    

    NOTE: string element should be one root element, that wraps others

    <div> ... </div>
    

    not

    <div></div><div></div>
    


    0 讨论(0)
  • 2021-01-13 19:35

    I assume you can create a div and then modify the div.innerHTML to have the content of the response:

    function importHTML(url_) {
      var request = new XMLHttpRequest();
    
      request.addEventListener("load", function(event_) {
    
        var myDiv = document.createElement("div")
        myDiv.innerHTML = this.responseText
    
        document.body.appendChild(myDiv);
      }, false);
    
      xmlhttprequest.open("POST", url_, true);
      xmlhttprequest.send(null);
    }
    
    0 讨论(0)
  • 2021-01-13 19:47

    Ajax HTML Injection

    jQuery $.get() and JavaScript XMLHttpRequest()

    This is a demonstration of 2 ways to inject, include, import, etc. There's 3 pages:

    1. index.html
      • It has 2 links and 2 divs
    2. data1.html
      • It's data will be imported to index.html by $.get()
    3. data2.html
      • It's data will be imported to index.html by XMLHttpRequest()

    I added jQuery to show the difference in complexity, but they do the same thing. The live demo is at the end of this mess.

    jQuery $.get() Setup

    HTML on index.html

    div#data1 is the element that'll have the HTML of data1.html appended to it.

         <h3 id="import1">
            <a href="">Import data1.html by jQuery<code>$.get()</code></a>
         </h3>
         <div id="data1"></div>
    

    jQuery on index.html

    $('#import1').on('click', function(e) {
        e.preventDefault();
        $.get('data1.html', function(data) {
            $("#data1").html(data);
        });
    });     
    

    JavaScript XMLHttpRequest() Setup

    HTML on index.html

    div[data-x] is the element that'll have the HTML of data2.html appended to it.

    <h3 id="import2">
        <a href="">
            Import data2.html by JavaScript<code>XMLHttpRequest()</code>
        </a></h3>
    <div data-x="data2.html"></div>
    

    javaScript on index.html

              function xhr() {
                 var tags, i, clone, file, xhttp;
                 tags = document.getElementsByTagName("*");
                 for (i = 0; i < tags.length; i++) {
                   if (tags[i].getAttribute("data-x")) {
                     clone = tags[i].cloneNode(false);
                     file = tags[i].getAttribute("data-x");
                     xhttp = new XMLHttpRequest();
                     xhttp.onreadystatechange = function() {
                     if (xhttp.readyState == 4 && xhttp.status == 200) {
                       clone.removeAttribute("data-x");
                       clone.innerHTML = xhttp.responseText;
                       tags[i].parentNode.replaceChild(clone, tags[i]);
                       xhr();
                     }
                    }
                    xhttp.open("GET", file, true);
                    xhttp.send();
                    return;
                  }
                }
              }
    
    
         document.getElementById('import2').addEventListener('click', function(e) {
           e.preventDefault();
           xhr();
         }, false);
    

    README.md

    Plunker

    Note: This demo relies on user interaction via anchor links. This of course is probably not exactly what you need. You probably want it automatically loaded, so the following modifications are needed:

    jQuery

    $(function() {
        $.get('data1.html', function(data) {
            $("#data1").html(data);
        });
    });
    

    JavaScript

    (function xhr() {
            xhr();
                 var tags, i, clone, file, xhttp;
                 tags = document.getElementsByTagName("*");
                 for (i = 0; i < tags.length; i++) {
                   if (tags[i].getAttribute("data-x")) {
                     clone = tags[i].cloneNode(false);
                     file = tags[i].getAttribute("data-x");
                     xhttp = new XMLHttpRequest();
                     xhttp.onreadystatechange = function() {
                     if (xhttp.readyState == 4 && xhttp.status == 200) {
                       clone.removeAttribute("data-x");
                       clone.innerHTML = xhttp.responseText;
                       tags[i].parentNode.replaceChild(clone, tags[i]);
                       xhr();
                     }
                    }
                    xhttp.open("GET", file, true);
                    xhttp.send();
                    return;
                  }
                }
              })();
    
    0 讨论(0)
  • 2021-01-13 19:47

    The importHTML.js file will look like this :

    function importHTML(url_) {
      var request = new XMLHttpRequest();
      request.addEventListener("load", function(event_) {
      var iDiv = document.createElement('div');
    iDiv.innerHTML = this.responseText;
    document.getElementsByTagName('body')[0].appendChild(iDiv);
      }, false);
    
      request.open("POST", url_, true);
      request.send(null);
         }
    
    0 讨论(0)
  • 2021-01-13 19:53

    Interestingly there is an upcoming W3C draft for HTML imports https://www.w3.org/TR/html-imports/

    Until then we can append the required markup to the DOM using Javascript.

    JQuery approach

    $(document).ready(function(){
        $( "body" ).load( "navbar.html" );
    });
    
    0 讨论(0)
  • 2021-01-13 19:56

    you need a reference to DOM to know where to innest your loaded page. in your case you could think about appending it to body like this:

    function importHTML(url_) {
      var request = new XMLHttpRequest();
    
      request.addEventListener("load", function(event_) {
    
        document.body.innerHTML += this.responseText
    
      }, false);
    
      xmlhttprequest.open("POST", url_, true);
      xmlhttprequest.send(null);
    }
    
    0 讨论(0)
提交回复
热议问题