纯Javascript中的jQuery .load template.html

时间:2015-12-17 09:24:43

标签: javascript jquery

我目前正在加载这样的模板:

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

我目前正在使用jQuery,但是如何在纯Javascript中执行相同的操作?

1 个答案:

答案 0 :(得分:3)

使用纯javascript ajax并在onreadychange()事件中将innerHTML mydiv属性设置为ajax响应的内容

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