如何从 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
How to call a javascript function from a JSON string?
提问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 functionDeclaractionAsString
would 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 eval
to execute the given string as code:
您可以使用 evileval
将给定的字符串作为代码执行:
if (data.HasCallback) {
eval("("+data.Callback+"());");
}
The additional parentheses at the end execute your function immediately.
最后的附加括号立即执行您的函数。