且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从使用AJAX加载的文档追加HTML?

更新时间:2023-12-05 17:07:46

Ajax HTML注入



jQuery $。get()和JavaScript XMLHttpRequest()

这是2种注入,包含,导入等方式的演示。共有3页:


  1. index.html


    • 它有2个连结和2个div


  2. data1.html


    • 数据将通过 $导入到index.html。 get()


  3. data2.html


    • 它的数据将通过 XMLHttpRequest()

  4. 导入到index.html中。

我添加了jQuery来显示复杂性的差异,但他们也做了同样的事情。现场演示结束了这场混乱。


jQuery $。get() 设置

blockquote>

index.html上的HTML
$ b div#data1 是添加了data1.html HTML的元素。

 < h3 ID = import1 &GT; 
< a href =>通过jQuery< code> $。get()< / code>< / a>导入data1.html。
< / h3>
< div id =data1>< / div>

index.html上的jQuery


$ ('click',function(e){
e.preventDefault();
$。$ b pre $ $('#import1')。 get('data1.html',function(data){
$(#data1)。html(data);
});
});







JavaScript XMLHttpRequest() 设置


index.html上的HTML



div [data-x] 是添加了data2.html的HTML元素。

 < h3 id =import2> 
< a href =>
通过JavaScript导入data2.html< code> XMLHttpRequest()< / code>
< / a>< / h3>
< div data-x =data2.html>< / div>

index.html上的javaScript

  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(假);
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;




$ b document.getElementById('import2')。addEventListener('click',function(e){
e.preventDefault();
xhr();
},false);

README.md



Plunker b b 依靠锚链接进行用户交互。这当然可能不是你所需要的。您可能希望它自动加载,所以需要进行以下修改:

jQuery

$(function(){
$ .get('data1.html',function(data){
$(#data1)。html数据);
});
});

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 =(函数(){
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;
}
}
})();


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 simple JavaScript function.

Here is the content of my nav bar, the content I want to reuse:

<div id = "navbar">
  <div class = "Tab">
    <h1>Home</h1>
  </div>
  <div class = "Tab">
    <h1>Contact</h1>
  </div
</div>

That is in a file called navbar.html

Now in my main index.html I want to import it by doing something like this:

<head>
  <script src = "importHTML.js" type = "text/javascript"></script>
</head>

<body>
  <script type = "text/javascript">
    importHTML("navbar.html");
  </script>
</body>

That should take care of importing the html in navbar.html.

The content of importHTML.js is this:

function importHTML(url_) {
  var request = new XMLHttpRequest();

  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?  
    document.body.appendChild(this.responseText);
  }, false);

  xmlhttprequest.open("POST", url_, true);
  xmlhttprequest.send(null);
}

So, I guess my question is pretty simple: How do I convert that response text to an HTML element so I can append all of it to the body?

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;
              }
            }
          })();