Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
14
rated 0 times [  15] [ 1]  / answers: 1 / hits: 76045  / 14 Years ago, fri, october 15, 2010, 12:00:00

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.


More From » jquery

 Answers
14

Here's a working example



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();
});​

[#95294] Thursday, October 14, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parker

Total Points: 259
Total Questions: 109
Total Answers: 97

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;