Ajax响应:数据(JSON,XML)或HTML片段? [英] The AJAX response: Data (JSON, XML) or HTML snippet?

查看:122
本文介绍了Ajax响应:数据(JSON,XML)或HTML片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道什么是Ajax响应理想输出格式?纯数据(JSON,XML)渲染成使用一些客户端的JavaScript模板引擎的页面?或HTML片段呈现到页面原样?

I'm just wondering what is an "ideal" output format for the AJAX response? Pure data (JSON, XML) rendered into the page using some client-side JavaScript template engine? Or an HTML snippet rendered into the page "as-is"?

你是什么preference为什么?

What is your preference and why?

推荐答案

在大多数情况下,你只需要(,我使用JSON作为一个例子或XML如适用)。发送JSON

In most scenarios you need to only send JSON (or XML as appropriate, I am using JSON as an example).

  • 如果您要发送的数据,如股票价格,使用JSON。
  • 如果你想保持网络层很瘦然后把纯JSON数据,让客户做加标记的繁重工作。
  • 如果客户端页面是持久性的,然后发送JSON。然后,客户机可以发送一个问候Person.Name。它可以刷新Person.Score或显示一个表单编辑Person.Status,所有的处理只是一个人的对象。
  • 如果您在暴露网络的API,显然是使用JSON,所以客户端可以做任何他们想做的事情。

现在这么说,我真的不喜欢从JavaScript生成HTML。这是一个维护的噩梦,我根本不喜欢混合两种。那么,如何避免生成HTML在JavaScript中,如果你要发送的JSON?如果你正在处理的人(S)的对象,当你第一次在渲染页面,你会呈现为这样的:

Now that said, I really dislike generating HTML from JavaScript. It's a maintenance nightmare and I simply don't like mixing the two. So how do you avoid generating the HTML in JavaScript if all you are sending is JSON? If you are dealing with Person(s) object, when you first the render the page, you would render it as such:

...
<div class="person display">
    <div class="name"></div>
    <div class="status"></div>
    <div class="score"></div>
</div>
...

当你通过AJAX的人的数据,只是填充上述DOM结构。

When you get the person data via AJAX, just populate the above DOM structure.

如果你想显示的信息多个人,然后,而不是直接填充DOM结构,你应该做它的一个克隆,然后填充它。这样你的模板保持不变,你可以重新使用它。

If you wish to display information for multiple Persons then instead of populating the DOM structure directly, you should make a clone of it and then populate it. This way your template stays intact and you can re-use it.

这篇关于Ajax响应:数据(JSON,XML)或HTML片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆