0

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

Steve Campbell
  • 3,385
  • 1
  • 31
  • 43
user878844
  • 189
  • 2
  • 11
  • 1
    Yes, it is a limitation of JSON that it only works with values, not functions. Your workaround should work with some tweaks though. – Steve Campbell Sep 04 '12 at 15:18

2 Answers2

1

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.

Community
  • 1
  • 1
Manuel Leuenberger
  • 2,327
  • 3
  • 21
  • 27
0

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?

Community
  • 1
  • 1
Pandaiolo
  • 11,165
  • 5
  • 38
  • 70