Performing jQuery val() against a textbox with htm

2019-08-27 03:49发布

I have set up my issue using a simple js fiddle http://jsfiddle.net/um788f6q/

<input type="text" id="yo">
$("#yo").val('hell&#39;o')

Basically I would like to know if there is a way to display an apostrophe rather than the encoded string. I have encoded the values like this on the server to prevent xss attacks, so decoding is not realy a valid option.

Thanks

4条回答
够拽才男人
2楼-- · 2019-08-27 04:23

This should help you

var tp = 'hell&#39;o';
var new_tp = $('<textarea />').html(tp).text();
$('#yo').val(new_tp); 

JS Fiddle

查看更多
太酷不给撩
3楼-- · 2019-08-27 04:28

Try this

var test = 'hell&#39;o';
var decoded = $('<div/>').html(test).text();
$("#yo").val(decoded);

Fiddle Demo

查看更多
混吃等死
4楼-- · 2019-08-27 04:41

Basically I would like to know if there is a way to display an apostrophe rather than the encoded string.

Nothing sane.

The value property deals in text, not HTML.

As a horrible hack you could convert it to text by parsing the HTML and then reading the resulting text node.

$("#yo").val($("<div />").html('hell&#39;o').text());

… but don't. Solve the real problem instead.

I have encoded the values like this on the server to prevent xss attacks

Don't do that.

You're inserting the data into JavaScript, not into HTML.

Don't use a defence for HTML when you aren't dealing in HTML. It could leave you vulnerable.

The appropriate way to encode data for inserting into JavaScript is to use a JSON encoder. (Then encode the resulting JSON with entities if you are putting the JSON in an HTML attribute value, or escape any / characters if you are putting it in a <script> element).

查看更多
霸刀☆藐视天下
5楼-- · 2019-08-27 04:47

You can replace $#39; by ' in JS and replace it back on the server side.

<input type="text" id="yo">
$("#yo").val('hell&#39;o'.replace('&#39;',"'"))
查看更多
登录 后发表回答