I am making an AJAX call with jQuery to a PHP script that needs to return javascript code embedded in a JSON result for the jQuery code to execute. How do I go about passing javascript code in JSON?
+1
A:
Two ways:
- You'll have to pass it as a string and use
eval()
on the client side. - You can use JSONP, and instead of doing a call, have your client side script insert a
<script>
with itssrc
pointing to the server-side code that returns the new script.
In either case, make sure you secure it well - if the user can somehow insert their own code into your response, they could do some damage.
Max Shawabkeh
2010-02-06 08:09:21
Is eval slower than just including the script the standard way? Of both of your suggestions, which is better and why?
Chetan
2010-02-06 08:19:28
JSONP would be marginally faster, and is used more often, but it's open to XSS attacks if you aren't careful. Myself, I wouldn't go with either and instead pass data that describes what I need to do to some existing function (see David's comment on your question).
Max Shawabkeh
2010-02-06 08:22:39
A:
The definition of JSON doesn't allow for javascript functions to be transported. It is meant to be language independent. If you use a JSON parser rather than eval(), it will fail if the JSON contains any functions.
Douglas Crockford, who I believe coined the term JSON has a JSON parser for javascript
Even JSONP doesn't return a function but a function call - myFuncIAskedFor({ returned JSON })
As others have mentioned, define your functions locally, it's the safest thing to do
Also use a JSON parser
meouw
2010-02-06 08:45:08