通常在 ExtJS 应用程序上转义 HTML 的最佳方法是什么? [英] What is the best way to escape HTML on ExtJS application generally?

查看:31
本文介绍了通常在 ExtJS 应用程序上转义 HTML 的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ExtJS 开发一个 Web 应用程序来构建 GUI 并通过 RESTful Web 服务与服务器通信(返回的数据被格式化为 JSON 对象).
现在我在处理包含 HTML 标签、Javascript 代码的数据时遇到问题;因为当我将这些值设置为 Ext 表单、标签、输入字段时,它们会受到这些语法的影响.
我使用这个函数从模型对象加载数据到表单:

I am developing a web application using ExtJS to build GUI and communicate with server via RESTful web-service (the returned data is formatted as JSON objects).
Now I am having problems when processing with data which contains HTML tags, Javascript codes inside; because when I set those values to Ext forms, labels, input fields, they are affected by those syntaxes.
I used this function to load data from model object to form:

form.loadRecord(model);

我找到了转义 HTML 和 JS 的解决方案:使用

I have found a solution to escape HTML and JS: using

field.setValue(Ext.util.Format.htmlDecode(data)); 

但我认为这对于整个应用程序来说不是一个好的解决方案,因为开发人员必须做很多事情:检查所有输入字段、标签,并将该片段放入其中.毕竟,这不是构建快速、健壮和可维护的应用程序的好方法.
那么,请您帮我解决一下,以便可以在一个地方修改它,并影响其他地方.我可以覆盖 AbstractComponent 的 setValue/setLabel 吗?或者我应该在渲染数据之前对数据进行编码?以及如何解码这些数据?(P/S:我在服务器端使用Grails框架)非常感谢.

but I think that is not a good solution for whole application, because the developers must do so much things: review all input fields, labels, and put that snippet to them. And after all, that is not a beautiful way to build a fast, robust and maintainable application.
So, could you please help me solution so that it can be modified at one place, and affects to the rest. Can I override the setValue/ setLabel of AbstractComponent? Or should I encode the data before rendering them? And how to decode those data? (P/S: I uses Grails framework on the server-side) Thank you so much.

推荐答案

一切都取决于您的用例,但我所做的是 - 在服务器端转义所有 HTML 代码,以便不会错误地忘记"地方.当这些数据需要在表单字段中加载时,这当然会产生问题,因为它们被转义了.最简单的解决方案是覆盖所有表单字段的 setValue 并使用 Extjs htmlDecode 函数,这会将这些值恢复为正常.

Everything depends on your use case, but what I do is - escape all HTML code on server side, so that there are no 'forgotten' places by mistake. That of course creates problems, when these data need to be loaded in form fields, because they are escaped. The easiest solution is to override setValue for all form fields and use Extjs htmlDecode function, which will revert these values back to normal.

Ext.override(Ext.form.field.Base, {
    setValue: function(val) {
        val = Ext.util.Format.htmlDecode(val);
        return this.callParent([val]);
    }
});

这篇关于通常在 ExtJS 应用程序上转义 HTML 的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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