Live preview of formatted HTML form input with Rai

2019-06-06 03:21发布

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.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-06 03:38

You could also consider using something like textile or markdown, which are ways to achieve HTML markup with plain text.

查看更多
We Are One
3楼-- · 2019-06-06 03:46

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.

查看更多
登录 后发表回答