AJAX读取模板文件并替换模板中的标签

下载地址

http://pan.baidu.com/share/link?shareid=238886&uk=1680261748

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>AJAX读取模板文件并替换模板中的标签</title>
<script src="js/ajax.js"></script>
<script>
window.onload = function () {
tmpl2html(onLoad);
};

function onLoad(str) {
var json1 = {tit: '这是模板文件template1.tml中的{tag:tit1}标签替换后的内容', con: '这是模板文件template1.tml中的{tag:con1}标签替换后的内容'};
var json2 = {tit: '这是模板文件template2.tml中的{tag:tit2}标签替换后的内容', con: '这是模板文件template2.tml中的{tag:con2}标签替换后的内容'};

var html = document.body.innerHTML;

html = format(html, {
tit1: json1.tit,
con1: json1.con,
tit2: json2.tit,
con2: json2.con
});

document.body.innerHTML = html;
}

function tmpl2html(fn) {
var html = document.body.innerHTML;

var tmpl = html.match(/&lt;%html ([^;]+) %&gt;/ig);

for (var i = 0; i < tmpl.length; i++) {
(function (i) {
var url = tmpl[i].replace(/&lt;%html /ig, '').replace(/ %&gt;/ig, '');

ajax(url, function (res) {
html = html.replace(new RegExp('&lt;%html ' + url + ' %&gt;', 'ig'), function (str) {
return res;
});

document.body.innerHTML = html;

if (i == tmpl.length - 1) fn(html);
}, function () {
alert('404');
});
})(i);
}
}

function format(str, json) {
for (var i in json) {
var re = new RegExp('{tag:' + i + '}', 'g');

str = str.replace(re, json[i]);
}

return str;
}
</script>
</head>

<body>
用AJAX从服务器文件读取模板文件,并替换模板中的标签。<br /><br /><%html template1.tml %><br /><%html template2.tml %>
</body>
</html>

 

template1.tml

<div>{tag:tit1}</div>
<div>{tag:con1}</div>

 

template2.tml

<div>{tag:tit2}</div>
<div>{tag:con2}</div>

 

ajax.js

function ajax(sURL, fnOnSucess, fnOnFail)
{
var oAjax = null;

if(window.ActiveXObject)
{
oAjax = new ActiveXObject('Microsoft.XMLHTTP');
}
else
{
oAjax = new XMLHttpRequest();
}

oAjax.open('GET', sURL, true);

oAjax.onreadystatechange = function () {
if(oAjax.readyState == 4)
{
if(oAjax.status == 200)
{
fnOnSucess(oAjax.responseText);
}
else
{
fnOnFail(oAjax.status);
}
}
};

oAjax.send(null);
}

function ajaxPost(sURL, data, fnOnSucess, fnOnFail)
{
var oAjax = null;

if(window.ActiveXObject)
{
oAjax = new ActiveXObject('Microsoft.XMLHTTP');
}
else
{
oAjax = new XMLHttpRequest();
}

oAjax.open('POST', sUrl, true);

oAjax.onreadystatechange = function () {
if(oAjax.readyState == 4)
{
if(oAjax.status == 200)
{
fnOnScuess(oAjax.responseText);
}
else
{
fnOnFail(oAjax.status);
}
}
};

oAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

oAjax.send(data);
}

posted @ 2013-02-18 17:32  baiezone  阅读(473)  评论(0编辑  收藏  举报