如何优雅地处理 Ajax 请求响应中的 JSON 对象?
我对使用 JSON 处理 Ajax 请求和响应周期非常陌生。 我之前只使用过作为 POST 数据传递的普通旧参数,并且在响应中直接渲染 HTML,然后将其放入 DOM 中。 当我查看各种示例并阅读各种教程时,这似乎是一种相当常见的做法,即简单地从与硬编码到字符串中的 HTML 混合的 JSON 对象构建字符串,然后将字符串作为 innerHTML 分配给某个元素。
一个常见的示例如下所示:
var jo = eval(req.responseText);
var strTxt = '<span>' + jo.f_name + ' ' + jo.l_name + '</span><br/>' + 'Your Age Is: ' + jo.age + '<br/>';
$('myDiv').innerHTML = strTxt;
是否有更优雅(或更正确)的方式来处理 JSON 响应,以便我不用在 javascript 中对 HTML 进行硬编码? 或者说人们就是这么做的?
PS 教程或其他来源的链接值得赞赏。
I'm really new to using JSON to handle my Ajax Request and Response cycle. I've previously used just plain old parameters passed as POST data and I've rendered straight HTML in the response which was then placed into the DOM. As I've looked at various examples and read through various tutorials, it seems like a fairly common practice to simply build a string from the JSON object mixed with HTML that's been hard coded into the string and then assign the string as innerHTML to some element.
A common example looks something like this:
var jo = eval(req.responseText);
var strTxt = '<span>' + jo.f_name + ' ' + jo.l_name + '</span><br/>' + 'Your Age Is: ' + jo.age + '<br/>';
$('myDiv').innerHTML = strTxt;
Is there a more elegant (or correct) way of handling the JSON response so that I'm not hard coding HTML in the javascript? Or is this pretty much how people do it?
P.S. Links to tutorials or other sources are appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从 JSON 创建的对象是标准的 Javascript 对象,因此您可以轻松使用 jQuery 选择器来创建或访问 DOM 元素并插入 JSON 对象中的内容。
例如。
The objects created from JSON are standard Javascript objects, therefore you can easily use jQuery selectors to create or access DOM elements and insert content from your JSON objects.
eg.
我避免在 JavaScript 字符串中编写大量 HTML。 我更喜欢将结构与数据操作分开。 更好的选择是将该代码放置在页面中,根据 ID 加载值,并在必要时显示/隐藏它:
这可能不完全是您想要做的,但您明白了。
I steer away from writing a lot of HTML within JavaScript strings. I prefer separation of structure from data manipulation. The better alternative is to place that code in the page, load the values based off the ID's, and show/hide it if necessary:
That might not be exactly what you want to do but you get the idea.
您可以使用 javascript 在 DOM 中创建元素,而不是仅仅将它们放入 DIV 的 innerHtml 中,如下所示(未经测试):
You could create the elements in the DOM using javascript instead of just dropping them into the innerHtml of the DIV, something like the following (untested):
您可以查看模板引擎,例如 PURE - 一开始可能有点难以进入,但它支持许多主要的 javascript 框架(还有很好的 DOMAssistant)并将 html 与数据分开。
You could check out a templating engine such as PURE - may be a bit hard to get into at first but it supports many major javascript frameworks (and DOMAssistant which is nice) and separates html from the data.