jQuery .load template.html in pure Javascript [closed]

独自空忆成欢 提交于 2021-02-07 18:28:22

问题


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?


回答1:


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" );


来源:https://stackoverflow.com/questions/34330919/jquery-load-template-html-in-pure-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!