最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to invoke a function, whose name is passed in Json object? - Stack Overflow

programmeradmin3浏览0评论

I have a JSON object with a key element called callback.

{
"id":34,
"description":"",
"item_id":4,
"callback":"addNew",
"filename":"0000072.doc",
"type":"News",
"ext":"doc",
"size":46592
}

I would like to call the javascript "addNew" function. I tried.

json.callback(json);

But does not work. Any idea?

I have a JSON object with a key element called callback.

{
"id":34,
"description":"",
"item_id":4,
"callback":"addNew",
"filename":"0000072.doc",
"type":"News",
"ext":"doc",
"size":46592
}

I would like to call the javascript "addNew" function. I tried.

json.callback(json);

But does not work. Any idea?

Share Improve this question asked Jun 4, 2009 at 11:07 Sergio del AmoSergio del Amo 78.1k68 gold badges153 silver badges180 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 12

Assuming it is a global function (it shouldn't be):

window[json.callback](json);

If your code is well structured you will probably have an object containing all the functions the JSON could call.

var myObject = {
  func1: function myObject_func1_method(foo) {
    return 1;
  },
  func2: function myObject_func2_method(foo) {
    return 2;
  }
}

Then you can:

myObject[json.callback](json);

Don't use eval, use

window[json.callback](json); 

If the function is in the global scope. Use the scope instead of window otherwise.

Use eval(json.callback+'()');

发布评论

评论列表(0)

  1. 暂无评论