Importing external HTML inner content with Javascr

2019-08-07 14:17发布

问题:

I need some help, I've got the following HTML code:

<ul class="menu-list">
  <li class="active"><a href="cont1.html" title="Title 1">Link 1</a></li>
  <li><a href="cont2.html" title="Title 2">Link 2</a></li>
  <li><a href="cont3.html" title="Title 3">Link 3</a></li>
  <li><a href="cont4.html" title="Title 4">Link 4</a></li>
</ul>

<div class="content">           
   <div class="innerContent">
        <!-- Insert external HTML content here -->
   </div>
</div>

So, when I click "Link 1", for example, I need to get the inner content from "cont1.html" to be appended inside of the div class="innerContent", not forgetting to add the "class="active"" inside the clicked li. Using just Javascript/AJAX without Jquery and without changing this HTML.

I did a similar example here, but is working for the content of the same page, not different pages, and I don't know why but doesn't work on IE.

Please, someone can help me?

回答1:

Try this

  <ul class="menu-list">
   <li class="active"><a href="javascript:display('cont1.html');" title="Title 1" >Link 1</a></li>
   <li><a href="javascript:display('cont2.html');" title="Title 2" >Link 2</a></li>
   <li><a href="javascript:display('cont3.html');" title="Title 3" >Link 3</a></li>
   <li><a href="javascript:display('cont4.html');" title="Title 4" >Link 4</a></li>
  </ul>

<div class="content">           
  <div class="innerContent" id="innerContent">
  </div>
</div>

javaScript

function display(url)
{
   var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
           xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("innerContent").innerHTML=xmlhttp.responseText;
        }
      }
    xmlhttp.open("GET",url,true);
    xmlhttp.send();
}


回答2:

It sounds to me like you want to make an AJAX request for the external file, then use the responseText to populate the innerHTML of your container.

This article guides you through how to make that an XMLHttpRequest -- AJAX without jQuery: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest

So you'll have to create a function, which runs when you click one of those links, that will 1) perform the AJAX request to get the external HTML; 2) populate your innerContent <div> with the responseText; and 3) change which <li> is classed "active".