如何从 JSON 字符串调用 javascript 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5494127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:23:08  来源:igfitidea点击:

How to call a javascript function from a JSON string?

javascriptjqueryajaxxmlhttprequesthttp-post

提问by smartcaveman

If I do an AJAX post with jQuery that looks like

如果我用 jQuery 做一个 AJAX 帖子,看起来像

 $.post('MyApp/GetPostResult.json', function(data) {
    // what goes here?
 });

and the result looks like

结果看起来像

{
    "HasCallback": true,
    "Callback": "function(){ alert('I came from the server'); }"
};

Then how do I call the Callback function? Can I just write if(data.HasCallback){data.Callback();}?

那么如何调用Callback函数呢?我可以只写if(data.HasCallback){data.Callback();}吗?

采纳答案by Sophie Alpert

This should work:

这应该有效:

function(data) {
  if(data.HasCallback) {
    eval(data.Callback);
  }
}

Edit: Didn't look quite carefully enough. If you're indeed getting the function() { ... }text, then you need to eval(data.Callback + "()").

编辑:看起来不够仔细。如果您确实收到了function() { ... }文本,那么您需要eval(data.Callback + "()").

回答by André Pena

eval("(" + functionDeclarationAsString + ")()");

while functionDeclaractionAsStringwould be something in the form of function(){ alert('I came from the server'); }

functionDeclaractionAsString将是某种形式的东西 function(){ alert('I came from the server'); }

EDIT

编辑

The notation (functionReference)(); is used to call a reference to a function. The following would be valid:

符号 (functionReference)(); 用于调用对函数的引用。以下是有效的:

(function() { alert('it works'); })();

The following also would be valid:

以下内容也是有效的:

var my_function = function(param) { alert(param); };
(my_function)('this is a parameter');

回答by jpsimons

It's a better idea to keep code and data separate. To use your example, why not have JSON like this:

将代码和数据分开是一个更好的主意。要使用您的示例,为什么不使用这样的 JSON:

{
    "Message": "I came from the server"
}

And in your JavaScript:

在你的 JavaScript 中:

$.post('MyApp/GetPostResult.json', function(data) {
    if (data.Message) {
        alert(data.Message);
    }
});

回答by mVChr

You can use the evil evalto execute the given string as code:

您可以使用 evileval将给定的字符串作为代码执行:

if (data.HasCallback) {
  eval("("+data.Callback+"());");
}

The additional parentheses at the end execute your function immediately.

最后的附加括号立即执行您的函数。

Documented at the evil w3schools

记录在邪恶的 w3schools