How to call a javascript function from a JSON string?
Solution 1
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 + "()")
.
Solution 2
eval("(" + functionDeclarationAsString + ")()");
while functionDeclaractionAsString
would be something in the form of
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:
(function() { alert('it works'); })();
The following also would be valid:
var my_function = function(param) { alert(param); };
(my_function)('this is a parameter');
Solution 3
It's a better idea to keep code and data separate. To use your example, why not have JSON like this:
{
"Message": "I came from the server"
}
And in your JavaScript:
$.post('MyApp/GetPostResult.json', function(data) {
if (data.Message) {
alert(data.Message);
}
});
smartcaveman
Does software exist? https://www.codementor.io/smartcaveman
Updated on June 05, 2022Comments
-
smartcaveman almost 2 years
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();}
?