Encode HTML before POST

心不动则不痛 提交于 2019-12-10 14:39:21

问题


I have the following script, which encodes some of the value it receives propertly, but it does not seem to encode double quotes.

How do I encode the full value properly before posting?

function htmlEncode(value){ 
    return $('<div/>').text(value).html(); 
} 

The above script give me this:

&lt;p&gt;Test&amp;nbsp; &lt;span style="color: #ffffff"&gt;&lt;strong&gt;&lt;span style="background-color: #ff0000"&gt;1+1+1=3&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;

I need it to give me this:

&lt;p&gt;Test&amp;nbsp; &lt;span style=&quot;color: #ffffff&quot;&gt;&lt;strong&gt;&lt;span style=&quot;background-color: #ff0000&quot;&gt;1+1+1=3&lt;/span&gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;

EDIT: Followup question: Encoded HTML in database back to page


回答1:


You shouldn't try to encode things with JavaScript.

You should encode it serverside.

Anything that can be done with JavaScript can be undone.

It is valid to encode it in JavaScript if you also check that it was encoded on the server, but keep in mind: JavaScript can be disabled.




回答2:


What George says is true. But, if you have to encode strings client-side, I'd suggest you use JavaScript's encodeURIComponent().




回答3:


I had a similar problem. I simply used the replace method in javascript. Here's a nice article to read: http://www.w3schools.com/jsref/jsref_replace.asp

Basically what the replace method does is it swaps or replaces the character it founds with what you indicate as replacement character(s).

So this:

var str=' " That " ';
str = str.replace(/"/g,'&quot;');

Once you log this into the console of your browser, you will get something like

&quot; That &quot;

And this:

var str=' " That " ';
str = str.replace(/"/g,'blahblahblah');

Once you log this into the console of your browser, you will get something like

blahblahblah That blahblahblah



回答4:


You can use this module in js, without requiring jQuery:

htmlencode




回答5:


You can re-use functions from php.js project - htmlentities and get_html_translation_table




回答6:


Use escape(str) at client side

and

HttpUtility.UrlDecode(str, System.Text.Encoding.Default); at server side

it worked for me.



来源:https://stackoverflow.com/questions/4899005/encode-html-before-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!