如何从 JSON 字符串调用 javascript 函数?
如果我使用 jQuery 执行 AJAX 发布
$.post('MyApp/GetPostResult.json', function(data) {
// what goes here?
});
,结果如下所示
{
"HasCallback": true,
"Callback": "function(){ alert('I came from the server'); }"
};
那么我如何调用回调函数?我可以只写 if(data.HasCallback){data.Callback();}
吗?
If I do an AJAX post with jQuery that looks like
$.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();}
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该有效:
编辑:看起来不够仔细。如果您确实获得了
function() { ... }
文本,那么您需要eval(data.Callback + "()")
。This should work:
Edit: Didn't look quite carefully enough. If you're indeed getting the
function() { ... }
text, then you need toeval(data.Callback + "()")
.而
functionDeclaractionAsString
的形式为function(){alert('我来自服务器'); }
编辑
符号 (functionReference)();用于调用函数的引用。以下内容将是有效的:
以下内容也将是有效的:
while
functionDeclaractionAsString
would be something in the form offunction(){ alert('I came from the server'); }
EDIT
The notation (functionReference)(); is used to call a reference to a function. The following would be valid:
The following also would be valid:
将代码和数据分开是一个更好的主意。要使用您的示例,为什么不使用这样的 JSON:
在您的 JavaScript 中:
It's a better idea to keep code and data separate. To use your example, why not have JSON like this:
And in your JavaScript:
您可以使用邪恶的
eval
将给定的字符串作为代码执行:末尾的附加括号立即执行您的函数。
记录在邪恶的 w3schools
You can use the evil
eval
to execute the given string as code:The additional parentheses at the end execute your function immediately.
Documented at the evil w3schools