我有一个包含文本区域的模式。当用户输入一些文本然后提交模式时,模式将关闭,我想将文本存储在 HTML 中的隐藏字段中。
安全地转义文本区域中的所有文本以存储在 HTML 属性中的最佳方法是什么?必须保留换行符。
如果用户再次打开模式,如何抓取存储在隐藏字段中的文本并将其按原样放回文本区域,并包含换行符?
当用户提交表单时,如何再次规范隐藏字段中的文本,以便可以使用它或将其以其原始形式(带有换行符)保存到数据库中?
里>
我愿意接受使用 JvaScript 存储 textarea 文本的替代解决方案,以最终将其传递给 PHP。
最佳答案
What is the best way to safely escape all the text from the textarea, for storage in an HTML attribute? New line characters must be preserved.
使用.val()
是最好的选择,它不会允许文本区域内容突破隐藏的值属性。使用 native Javascript .value
也将工作并且安全,.val()
只是一个包装。
If the user opens the modal again, how do I grab the text stored in the hidden field and put it back into the textarea as it was, complete with new line characters?
当模式打开时:
// #mytextarea = the textarea on the modal
// #myhidden = the hidden on the main page
$('#mytextarea').val($('#myhidden').val()); // set the modal textarea to the value of the hidden
当模式关闭或“保存”时:
$('#myhidden').val($('#mytextarea').val());
When the user submits the form, how do I normalise the text from the hidden field again so that it can be used or saved to the database in its original form, with new line characters?
您无需执行任何操作即可保留新行。使用准备好的语句只需将原始发布值保存到数据库中。当您在页面上的某个位置输出该值时,您可以将新行转换为 <br />
通过使用 PHP 的 nl2br()
。仅当您输出到输入值以外的任何内容时才需要转换新行。另外不要忘记通过 htmlspecialchars()
运行它防止 XSS。
关于php - 使用 jQuery 将 textarea 文本安全地存储在隐藏字段中,然后在 PHP 中使用该文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17234429/