如何从使用AJAX加载的文档追加HTML? [英] How do I append HTML from a document loaded with AJAX?

查看:164
本文介绍了如何从使用AJAX加载的文档追加HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将.html文件的内容追加到我的主页的正文中。基本上,我正在尝试创建一个可重用的html块,我可以使用简单的JavaScript函数将其加载到任何页面中。



这是我的导航栏的内容,我想重复使用的内容:

 < div id =navbar> 
< div class =Tab>
< h1>主页< / h1>
< / div>
< div class =Tab>
< h1>联络人< / h1>
< / div
< / div>

即在一个名为navbar.html的文件中



 < head> 

现在我在主要的index.html中导入它。
< script src =importHTML.jstype =text / javascript>< / script>
< / head>

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

这应该注意导入navbar.html中的html。



importHTML.js的内容是这样的:

 函数importHTML(url_){
var request = new XMLHttpRequest();

request.addEventListener(load,function(event_){
//这是问题行代码
//如何获取我的响应内容像一个元素?
document.body.appendChild(this.responseText);
},false);

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





$ b因此,我想我的问题很简单:如何转换该响应text to HTML元素,所以我可以把它全部附加到body?

解决方案

Ajax HTML注入



jQuery $。get()和JavaScript XMLHttpRequest()

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


  1. index.html


    • 它有2个连结和2个div


  2. data1.html


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


  3. data2.html


    • 它的数据将通过 XMLHttpRequest()

    • 导入到index.html中。

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


jQuery $。get() 设置

blockquote>

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

 < h3 ID = import1 > 
< 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

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

这篇关于如何从使用AJAX加载的文档追加HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆