问题
I want a feature of previewing some text with HTML tags and then storing the text in database. I know it is not a good idea to allow HTML in database, for XSS security reasons. What are the ways to achieve this?
I want a feature similar to the one we have in stackoverflow, where we can format our sourcecodes. Thanks.
回答1:
Recommended way:
Create an javascript event listener for the form on your html-page. Submit the input via ajax to your rails app, where the input gets rendered (for example by the same helper that will later render the output from the database).
Use a markup language like RedCloth/Textile to avoid XSS. It's also easier to type/understand for your users!
Your requested way:
Create an javascript event listener and write the contents of the form/input to another div.
The javascript you'll need depends on which library you use (Prototype or jQuery, for example).
Example:
Suppose you have a form with a textarea, <textarea id="text"></textarea>
, and a preview area div with <div id="preview"></div>
and you are using Prototype:
document.observe("dom:loaded", function() {
new Form.Element.Observer('text', 0.25,
function () {
$('preview').update($F('text'));
}
);
}
This will check the textarea every 250ms for changes and copy its input into the preview div.
Actually, you just need the code inside the function that is called with document.observe
(starting with new Form.Element.Observer...
. The document.observe
will call this code after the browser has finished building the DOM-tree.
回答2:
You could also consider using something like textile or markdown, which are ways to achieve HTML markup with plain text.
来源:https://stackoverflow.com/questions/5475862/live-preview-of-formatted-html-form-input-with-rails