当用户将鼠标悬停在特定链接上时,我希望显示一个弹出窗口。
为此,我首先通过Ajax从服务器请求特定的JSON数据。
服务器查询数据库,并使用htmlspecialchars()
和回声json_encode($data)
转义任何恰好是用户提供的数据。
客户端然后使用以下模板组装HTML。
然后客户端显示弹出窗口。
我的问题只与渲染模板有关。
是否有更好的方法可以提供以下一项或所有好处?
谢谢
function getTemplate(type,json) {
switch(type) {
case 'person':
return '<dl><dt>Name:</dt><dd>'+((d.firstname&&json.lastname)?json.firstname+' '+json.lastname:((json.firstname)?json.firstname:json.lastname))+'</dd>'
+'<dt>Account:</dt><dd>'+json.account_name+'</dd>'
+((json.title)?'<dt>Title:</dt><dd>'+json.title+'</dd>':'')
+'<dt>User Name:</dt><dd>'+json.username+'</dd>'
+'<dt>Password:</dt><dd>'+json.password+'</dd>'
+'<dt>Communication Method:</dt><dd>'+json.communication_method+'</dd>'
+((json.email)?'<dt>Email:</dt><dd>'+json.email+'</dd>':'')
+((json.account_phone)?'<dt>Account Phone:</dt><dd>'+ayb.display_phone(json.account_phone)+'</dd>':'')
+((json.phone)?'<dt>Direct Phone:</dt><dd>'+ayb.display_phone(json.phone)+'</dd>':'')
+((json.mobile_phone)?'<dt>Mobile Phone:</dt><dd>'+ayb.display_phone(json.mobile_phone)+'</dd>':'')
+((json.account_fax)?'<dt>Account Fax:</dt><dd>'+ayb.display_phone(json.account_fax)+'</dd>':'')
+((json.fax)?'<dt>Direct Fax:</dt><dd>'+ayb.display_phone(json.fax)+'</dd>':'')
+((json.address || json.location)?'<dt>Address:</dt><dd>'+json.address+((json.address && json.location)?'<br>':'')+json.location+'</dd>':'')
+'</dl>';
break;
case 'company':
return 'bla bla bla';
break;
case 'somethingElse':
return 'bla bla bla';
break;
return '<h1>Invalid Template</h1>';
}
}
答案 0 :(得分:1)
这是一个使用mustache.js:
http://plnkr.co/m0NyrpTcKhIicTt0FD4N
HTML:
<dl><dt>Name:</dt><dd>{{firstname}} {{lastname}} </dd>
<dt>Account:</dt><dd>{{account_name}}</dd>
{{#title}}
<dt>Title:</dt><dd>{{title}}</dd>
{{/title}}
<dt>User Name:</dt><dd>{{username}}</dd>
<dt>Password:</dt><dd>{{password}}</dd>
<dt>Communication Method:</dt><dd>{{communication_method}}</dd>
{{#email}}
<dt>Email:</dt><dd>{{email}}</dd>
{{/email}}
{{#account_phone}}
<dt>Account Phone:</dt><dd>{{#display_phone}}{{account_phone}}{{/display_phone}}</dd>
{{/account_phone}}
</script>
<script type="text/html" id="company">
bla bla
</script>
<script type="text/html" id="somethingElse">
somethingElse bla bla
</script>
json:
var json = {
"firstname": "Basha",
"lastname": "tasha",
"account_name":"presonal",
"title":"MR",
"username":"basha",
"password":"******",
"communication_method":"phone<b>xss safe</b>",
"account_phone": "1231231234"
};
JS:
$(document).ready(function () {
var output = $("#output");
type = "person";
var template = $("#"+type).html();
if(template == undefined) template = "<h1>Invalid Template</h1>";
//you can inject client side callback for phone render before calling Mustache.render(template,json)
json.display_phone= function () {
return function (val, render) {
var phone = render(val);
return phone.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
}
};
var html = Mustache.render(template, json);
output.append(html);
});
它的XSS安全
请注意,自定义方法是在json数据中发送的&#34; display_phone&#34;