user878844
user878844

Reputation: 199

jquery ajax getJson onSuccess use a function from the response

I have a js script simply getting a basic Json content page.js

{
"desc":"",
**"save":function(){alert(0);}**
}

then on success:function(data) I simply wanted to do data.save() but the onsuccess never gets called ?

'complete' does though but still my save function isn't evaluated ?

I tried writting it as a string : "save":"function(){alert(0);}" and applying it to eval onSuccess , but strangely it says function has no name

Is this a limitation -- we can't pass functions as part of the json reponse object?

even less execute them ? or am I simply doing something wrong

Thanks for the insight

Upvotes: 0

Views: 318

Answers (2)

Pandaiolo
Pandaiolo

Reputation: 11586

You can just eval alert(0), it should work (and set this as your "save" string in the JSON)

But you should avoid using eval as a workaround

Edit : this has already been answered here : Is it valid to define functions in JSON results?

Upvotes: 0

Manuel Leuenberger
Manuel Leuenberger

Reputation: 2367

JSON is a pure data definition language, so functions can not be part of a JSON object. See this question. Using eval() might work, but I'd strongly discourage you to use it, since it is unsafe. I'd propose you implement the behavior you want in an object, and then set the state of this object using the JSON you got from the server.

Upvotes: 1

Related Questions