问题
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