this is slightly better than eval as eval is evil ;)
(new Function(response.data))()
Using eval
is evil because there can be lots of security holes. You are executing code in global scope. Function
takes of this differently by executing in its own scope.
new Function
is also faster
in your case
$.ajax({
url: '@Url.Action("GetPropertyDataForInstance", "Local_Data")',
type: 'POST',
dataType: 'json',
data: instancePropertyRequest,
contentType: 'application/json; charset=utf-8',
success: function (response) {
(new Function(response.data))()
}
})
new Function
creates a new function from a raw text.
()()
executes the function immediately
i would also add some extra checks and headers if you get your functions with ajax.
check this.
https://stackoverflow.com/a/17468822/2450730
edit
if you want to pass params from ajax
//raw ajax response
var x='param';
alert(x)
if you want to pass params from inside the ajax (not good.)
success: function (response) {
var x='param';
(new Function(response.data))(x)
}
raw
alert(x);
edit 2
if you get a object with
1.the script
2.the params
then you need to define a argument name.in this case 'x'.
js
(new Function('x',response.script))(response.param)
RAW response.script
alert(x)
more arguments:
(new Function('a','b','c','alert(a+b+c)'))(1,2,3) // 123
TEST IT ... http://jsfiddle.net/pLQzd/
READ IT ... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
scroll to the bottom.
but as you get the object containing the function and the vars... from the same ajax call
i would simply create something already described.
RAW
var param='hello';
alert(param);
or even simpler
alert('hello');