[英]Filling image source urls in client side javascript templates using ajax requests
我正在尝试使用客户端模板库ust.js。 我想使用从服务器使用Ajax(Json格式)检索到的值来填充“ img”标签(代码中的{profile.picUrl})的“ src”属性。
问题在于,在进行Ajax调用之前,浏览器会尝试加载图像,从而导致HTTP 404响应(“ src”包含模板占位符)。 没有向服务器发送404请求,有没有办法做到这一点?
这是一个复制该问题的示例:
<body>
<div class="template">
hi {profile.user}
<img src="{profile.picUrl}" />
<div id="actions">
{#actions}
<a href="{url}">{text}</a><br /><br />
{/actions}
</div>
</div>
<script>
function fillTemplates(responsedat, status, xhr) {
if (status === "success") {
template = $('.template').html();
dust.compileFn(template,"t");
dust.render("t", responsedat, function (err,out) {
if (err) {
console.log(err);
return;
}
else {
$('.template').html(out);
}
});
$('.template').show();
}
}
$.get('landing.jsp', {}, fillTemplates);
$.ready(function () {
$('.template').hide();
});
</script>
</body>
PS:大括号({profile.user})中的名称用于按ust.js语法填充模板中的值
通常,当我看到使用客户端模板时,模板本身不是“活动” DOM的一部分。 它通常位于脚本块中,例如来自主干的示例: http : //coenraets.org/blog/2012/01/backbone-js-lessons-learned-and-improved-sample-app/
示例: http : //jsfiddle.net/Rj2Hd/1/
<html>
<body>
<script type="text/template" id="template">
hi {profile.user}
<img src="{profile.picUrl}" />
<div id="actions">
{#actions}
<a href="{url}">{text}</a><br /><br />
{/actions}
</div>
</script>
<script>
function fillTemplates(responsedat, status, xhr) {
if (status === "success") {
template = $('#template').html();
alert(template);
// your stuff here
}
}
$(function () {
fillTemplates(null, 'success', null);
});
</script>
</body>
</html>
如果您可以更改源的占位符值,它应该简单到给它一个真实的地址,或者直到您收到AJAX的答复才提供一个真实的地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.