Ajax Testing with JSFiddle - Using templating
by bgrins
HTML
<div class='wrapper'>
<p>JSONP is loaded from different domain</p>
<ul id='post'></ul>
</div>
<script id='templateEcho' type='text/html'>
<ul>
<% each(data, function(name, val) { %>
<li><%= name %>: <%= val %>
<% }) %>
</ul>
</script>
CSS
body {
font-family: Lucida Sans, Arial;
}
p, ul {
padding: 10px;
}
ul {
margin: 5px;
border: 2px dashed #999;
}
JavaScript
var templateEcho = $("#templateEcho").html();
$.getJSON('http://jsfiddle.net/echo/jsonp/?callback=?', {
text: 'some text',
par1: 'another text',
delay: 1
},
function(data) {
showSuccess(data);
}
);
function showSuccess(data) {
console.log(templateEcho);
var html = template(templateEcho, { data: data });
//$("#post").html('<ul>' + templated.join('') + '</ul>');
}
function each(o, fn) {
var results = [];
for (var i in o) {
results.push(fn(i, o[i]));
}
return results;
}
var templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g
};
function template(str, data) {
var c = templateSettings;
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(c.interpolate, function(match, code) {
return "'," + code.replace(/\\'/g, "'") + ",'";
})
.replace(c.evaluate || null, function(match, code) {
return "');" + code.replace(/\\'/g, "'")
.replace(/[\r\n\t]/g, ' ') + "__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');";
var func = new Function('obj', tmpl);
return data ? func(data) : func;
};