jquery - Javascript object payload - Stack Overflow

I have this snippet of code which is running with the success call of an $.ajax jquery call.success:fun

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
 |  Show 5 more ments

2 Answers 2

Reset to default 4

Sure 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

相关推荐

  • jquery - Javascript object payload - Stack Overflow

    I have this snippet of code which is running with the success call of an $.ajax jquery call.success:fun

    13小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信