How to call a javascript function from a JSON string?

。_饼干妹妹 提交于 2019-12-12 13:36:18

问题


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


回答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 + "()").




回答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');



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



回答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



来源:https://stackoverflow.com/questions/5494127/how-to-call-a-javascript-function-from-a-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!