Exit the eval argument

I use evalto assign the dynamic properties of an object.

property_name_1 = property1;
property_name_2 = property2;
property_value_1 = 1;
property_value_2 = 2;
var obj = new Object;

eval("obj."+property_name_1+"='"+property_value_1+"'");
eval("obj."+property_name_2+"='"+property_value_2+"'");

then i use this object as post data during ajax request.

It's all right, but as you know, the eval function is not safe, and I have to be avoided property_value_1, property_value_2. For example, it property_value_2 = "<a href=''>Yahoo!</a>"will result in an error.

What is the best way to do this?

thank

+3
source share
4 answers

The best way is not to use evalat all:

obj[property_name_1] = property_value_1;
obj[property_name_2] = property_value_2;

If you still want to, you need to escape apostrophes and backslashes to put values ​​in string literals:

eval("obj." + property_name_1 + "='" + property_value_1.replace(/\\/g,'\\\\').replace(/'/g,"\\'") + "'");
eval("obj." + property_name_2 + "='" + property_value_2.replace(/\\/g,'\\\\').replace(/'/g,"\\'") + "'");

(If you surround the letter string with quotes instead of apostrophes, you need to avoid quotes and backslashes.)

+5

eval?

:

obj[property_name_1] = property_value_1;
obj[property_name_2] = property_value_2;

- , \.

0

Try:

var obj = new Object();
obj[property_name] = property_value;
0
source

I would use an object literal:

var obj = {
    property_name_1: property_value_1, 
    property_name_2: property_value_2
};
-1
source

Source: https://habr.com/ru/post/1770294/


All Articles