在json中传递函数并执行 [英] pass function in json and execute
问题描述
有没有办法可以将函数作为json字符串传递(使用JSON.stringify进行转换),将其发送到另一个函数,解析json然后执行json中的函数?我正在使用jquery和javascript。
Is there any way that I can pass a function as a json string (conversion with JSON.stringify), send it to another function, parse the json and then execute the function that was in the json? I am using jquery and javascript.
推荐答案
这是一个有效的示例
基本上,你必须小心这类事情。如果您使用现有的javascript函数,将其转换为字符串,并对其进行评估,则可能会遇到函数重新声明问题。如果您只是从服务器中获取一个函数字符串并且想要运行它,那么您可以像我在jsfiddle上那样做:
Basically, you have to be careful with this sort of thing. If you take an extant javascript function, turn it to a string, and eval it, you might run into function redeclaration issues. If you are simply taking a function string from the server and you want to run it, you can do as I did on that jsfiddle:
Javascript
var myFunc = "function test() {alert('test');}";
$(document).ready(function() {
var data = new Object();
data.func = myFunc;
var jsonVal = $.toJSON(data);
var newObj = $.evalJSON(jsonVal);
eval(newObj.func);
test();
});
这篇关于在json中传递函数并执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!