HTML 转义 ajax/json 返回的数据
我正在使用 ajax 从后端检索一些数据。我得到的结果是 json。
然后我使用 jquery 将其添加到页面:
$(...).append('<H3>' + data.title + '</H3>')
我刚刚意识到 json 数据不是 HTML 转义的,这很糟糕。
我应该怎么办?
- HTML转义所有从后端返回的数据在json中?
- 连接字符串时是否在前端进行所有转义? (即将所有外部数据包装在转义函数中)
选项1意味着json中的数据并不是真正“正确”,它对HTML很有用,但它不包含真实数据。更糟糕的是,这意味着我不能只使用 json_encode() - 我首先必须遍历数组数据并转义所有内容。
选项2似乎更复杂,我担心我可能会错过一个地方。另一方面,这就是从 SQL 获取数据并用 PHP 构建数据时所做的事情,所以我想我已经习惯了。
请不要建议:
$(...).append($('<H3></H3>').text(data.title))
当您有很多级别的嵌套标签时,这种编写方法会变得笨拙。我喜欢编写 HTML,而不是 DOM 调用。
附言。我知道我需要一个 Javascript 模板库,但现在我需要通过字符串连接来实现。
I'm using ajax to retrieve some data from the backend. I get the result as json.
I then use jquery to add it to the page:
$(...).append('<H3>' + data.title + '</H3>')
And I just realized that the json data is not HTML escaped, which is bad.
What should I do?
- HTML escape all the data returned from the backend in the json?
- Do all the escaping on the frontend when concatenating strings? (i.e. wrap all external data in an escaping function)
Option 1 means the data in the json is not really "correct", it's useful for HTML, but it does not contain the real data. And worse, it means I can't just use json_encode() - I would first have to walk through the array data and escape everything.
Option 2 seems more complicated, and I'm worried I may miss a spot. On the other hand that's what you do when getting data from SQL and building it in PHP, so I guess I'm used to it.
Please do not suggest:
$(...).append($('<H3></H3>').text(data.title))
That method of writing becomes unwieldy when you have many levels of nested tags. I like to write HTML, not DOM calls.
PS. I know I need a Javascript templating library, but for right now I need to do it with string concatenation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个简单的 jQuery 扩展,它添加了带有 html 转义的
$append()
格式化方法:使用此方法,您可以编写:
并且数据将被转义。根据您的口味在上面添加盐和胡椒。
更新:您还需要这个:
Here is simple jQuery extension that adds
$append()
formatting method with html escapement:With this method you can write:
And the data will be escaped. Add salt and pepper to the above - to your taste.
Update: You will also need this:
嗯,我周末正在做一个开源项目。
我想这会符合你的要求。请在 http://tog2html.com 上查看
例如,在您的情况下,在获取 json obj (var data )。你可以这样做:
Well, I am sort of working on an open-source project on my weekends.
I think it would fit your demand. Please check it out at http://tog2html.com
For instance, in your case , after getting a json obj (var data). You can do something like :