Skip to content Skip to sidebar Skip to footer

How To Call A Javascript Function From A Json String?

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': t

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

Solution 4:

You can use the evil eval to execute the given string as code:

if (data.HasCallback) {
  eval("("+data.Callback+"());");
}

The additional parentheses at the end execute your function immediately.

Documented at the evil w3schools

Post a Comment for "How To Call A Javascript Function From A Json String?"