纯 Javascript 中的 jQuery .load template.html [英] jQuery .load template.html in pure Javascript
本文介绍了纯 Javascript 中的 jQuery .load template.html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在加载这样的模板:
I am currently loading a template like this:
$('#mydiv').load("template1.html")
我目前正在使用 jQuery,但如何在纯 Javascript 中做同样的事情?
I'm currently using jQuery, but how can I do the same thing in pure Javascript?
推荐答案
by using pure javascript ajax 并在 onreadychange()
事件中将 mydiv
的 innerHTML
属性设置为 ajax 响应的内容
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" );
这篇关于纯 Javascript 中的 jQuery .load template.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文