开发者

Encode HTML before POST

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&a开发者_运维知识库mp;gt;&lt;/strong&gt;&lt;/span&gt;&lt;/p&gt;

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


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.


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


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


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

htmlencode


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


Use escape(str) at client side

and

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

it worked for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜