简体   繁体   中英

How to guard against unsafe characters in javascript

I have code in which I heard that there are unsafe characters in my code.

var listItem = $.trim(list[i]);                                    
$("<option value='" + listItem + "'>" + listItem + "</option>").appendTo(selectlist);

This is in a loop, but basically I am hearing that "listItem" has a quote in it or "other disallowed unsafe characters"

This is javascript/jquery in a .net / razor environment. What are my options for "fixing" this?

I would suggest making a...

var $option = $('<option>')

to create the element, and then you can...

$option.val(listItem);
$option.text(listItem);

to set the value and display text. Doing it in this manner does not allow the html parser to try to parse the listItem value. It treats it as a simple string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM