简体   繁体   中英

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

I have these elements in my html code :

<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 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 .

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

<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; you are access the element using the ID attribute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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