简体   繁体   English

客户端与服务器端模板

[英]Client Side vs Server Side templating

I was wondering what the best option would be for doing ajax calls to update a list of usernames. 我想知道进行ajax调用以更新用户名列表的最佳选择是什么。 I can either 我可以

a. 一种。 do a ajax call and get the user object back and build the html and append it into a div 进行ajax调用并返回用户对象并构建html并将其附加到div中

build_html = function(obj) {
    html = 'username - ' + obj.username
    $('#container').append(html);
}

b. b。 do a ajax call and have the django return back the html. 进行ajax调用,让django返回html。

response = render_to_response ('user_item_template.html', {'user' : user})
return response._container

If the response is successful I then append this to the container div. 如果响应成功,则将其附加到容器div。

Are there any cons to doing it with method 'b' because depending on the situation building html in javascript can have problems such as unescaped characters and it's just messy in general. 使用方法'b'是否有任何弊端,因为根据情况在javascript中构建html可能会遇到诸如未转义的字符之类的问题,并且一般来说它只是一团糟。

Thanks 谢谢

If you're requesting something that will solely be used for generating HTML, then just return the HTML as the response. 如果您要求仅用于生成HTML的内容,则只需返回HTML作为响应即可。 No need to involve the client, and your server will invariably be faster at the generation, especially if caching is employed. 无需涉及客户端,并且服务器的生成速度总是会更快,尤其是在使用缓存的情况下。

If you need data from a response, ie stuff you can introspect later to make decisions in your JS, then you need to return JSON and handle the generation of any HTML client side. 如果您需要响应中的数据 ,即可以稍后进行内省以在JS中进行决策的内容,则需要返回JSON并处理任何HTML客户端的生成。

Basically, if you can get by with returning flat HTML, do it. 基本上,如果您可以通过返回纯HTML来完成此操作。

I'd say it depends... In most cases (especially if you care about mobile users with slow(er) connections) transferring less data is more important than the time spent parsing the JSON and generating the HTML client-side. 我会说这取决于...在大多数情况下(尤其是如果您关心连接速度较慢的移动用户),传输较少的数据比解析JSON和生成HTML客户端所花费的时间更为重要。

Recommended read: http://ryanflorence.com/2012/client-v-server-templating/ 推荐阅读: http : //ryanflorence.com/2012/client-v-server-templating/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM