I have this snippet of code which is running with the success call of an $.ajax jquery call.
success:function(results){
if(options.payload)
{
eval("AddReview."+options.payload+"("+results+")");
}
}
The results variable can contain html and does not seem to want to pass through to the function. Is this the correct way to do this or can you think of a better way? This method basically allows me to interface the jquery $.ajax functionality with variable function payloads. Or in this case Object function payloads.
I have this snippet of code which is running with the success call of an $.ajax jquery call.
success:function(results){
if(options.payload)
{
eval("AddReview."+options.payload+"("+results+")");
}
}
The results variable can contain html and does not seem to want to pass through to the function. Is this the correct way to do this or can you think of a better way? This method basically allows me to interface the jquery $.ajax functionality with variable function payloads. Or in this case Object function payloads.
Share Improve this question asked Jan 21, 2013 at 22:38 DavidDavid 36.5k14 gold badges51 silver badges81 bronze badges 10-
Why can't you just use
AddReview[options.payload](results);
? – Shmiddty Commented Jan 21, 2013 at 22:40 -
What does
results
look like? – Blender Commented Jan 21, 2013 at 22:42 - @Blender I'm assuming a string given his example. – Austin Brunkhorst Commented Jan 21, 2013 at 22:42
-
1
@AustinBrunkhorst: Right, but if it looks like
'foo', 'bar'
, none of the answers will work. – Blender Commented Jan 21, 2013 at 22:44 - 1 Whenever you use eval: There IS a better way ;) – Sebastian vom Meer Commented Jan 21, 2013 at 23:15
2 Answers
Reset to default 4Sure there's a better way. There's no need for eval
in this case:
if (options.payload) {
AddReview[options.payload](results);
}
Objects are essentially associative arrays. Use this.
AddReview[options.payload](results);
As Blender mentioned, if results
is a list of string arguments such as 'hello', 'stack', 'overflow'
you can do this.
var addReview = AddReview[options.payload];
var args = $.map(results.split(','), function(arg) {
return $.trim(arg).substr(1, $.trim(arg).length - 2);
});
addReview.apply(addReview, args);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745429139a4627315.html
评论列表(0条)