4

I am currently loading a template like this:

$('#mydiv').load("template1.html")

I'm currently using jQuery, but how can I do the same thing in pure Javascript?

Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
Satch3000
  • 47,356
  • 86
  • 216
  • 346

1 Answers1

3

by using pure javascript ajax and in the onreadychange() event set the innerHTML property of mydiv to the contents of ajax response

function loadHTML(myDivId, url) {
    var xmlhttp;
    if (window.XMLHttpRequest) 
    {
        xmlhttp = new XMLHttpRequest();
    } 
    else 
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() 
    {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) 
        {
           if(xmlhttp.status == 200){
               document.getElementById(myDivId).innerHTML = xmlhttp.responseText;
               var allScripts = document.getElementById(myDivId).getElementsByTagName('script');
               for (var n = 0; n < allScripts .length; n++)
               {
                   eval(allScripts [n].innerHTML)//run script inside div generally not a good idea but these scripts are anyways intended to be executed.
               }
           }
           else {
               alert('Error');
           }
        }
    }

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

loadHTML( "mydiv", "template1.html" );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94