简体   繁体   English

单击时如何包含html文件代码 <li> 使用ajax和javascript?

[英]How to include an html file code on clicking on a <li> using ajax and javascript?

I have these elements in my html code : 我的html代码中有这些元素:

<ul class='tabs'>
  <li data-file='home'><a>Home</a></li>
  <li data-file='contact'><a>Contact</a></li>
   ..
   ..
</ul>

and I have a <div> called content: 我有一个<div>叫content:

<div class='content'>
   //Homepage Content
</div>

Then I use Javascript to get the content of the clicked <li> using data-file and then add .html for it so it become like this contact.html . 然后,我使用Javascript通过data-file获取被点击的<li>的内容,然后为其添加.html,使其变得类似于contact.html。

var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
                   if (xmlhttp.status == 200) {
                       document.getElementById('content').innerHTML = xmlhttp.responseText;

                   }
                   else if (xmlhttp.status == 400) {
                      alert('There was an error 400');
                   }
                   else {
                       alert('something else other than 200 was returned');
                   }
                }
            };

            xmlhttp.open("GET", file, true); // file is the variable 'contact.html'
            xmlhttp.send();

But I get an error : 但是我得到一个错误:

Uncaught TypeError: Cannot set property 'innerHTML' of null
    at XMLHttpRequest.xmlhttp.onreadystatechange 

Change your HTML to have an element with the specified ID 更改HTML以使其具有具有指定ID的元素

<div id='content'>
   //Homepage Content
</div>
<div class='content'>
   //Homepage Content
</div>

Above should be : 以上应为:

<div id='content'>
   //Homepage Content
</div>

Because here document.getElementById('content').innerHTML = xmlhttp.responseText; 因为在这里document.getElementById('content').innerHTML = xmlhttp.responseText; you are access the element using the ID attribute 您正在使用ID属性访问元素

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

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