Write a json string direct into the script tag
Is it possible to write a json string direct to the script tag?
My Solution:
myJsonObject = jQuery.parseJSON(' *json string* ');
stuffObject = myJsonObject.stuffObject;
delete myJsonObject.stuff开发者_如何转开发Object;
someObject = myJsonObject.someObject;
delete myJsonObject.someObject;
But i think it is a little bit dirty. Is there maybe a better (faster) solution?
Thanks!
All JSON is valid javascript (not always the other way around, though).
// These two lines are equivalent
var someObject = { a: 'a', b: 'b' };
var someObject = jQuery.parseJSON('{ "a": "a", "b": "b" }');
If you are getting your JSON string from a request to an external resource, I think what you are currently doing is the best way to do it. You could insert the JSON into a new script
element, if you really wanted, like so:
var $body = $(document.body);
$body.append("<script type='text/javascript'>var myJsonObject = " + jsonString + ";</script>");
I personally don't think this looks cleaner, but there are some other problems with this approach. If a hacker was able to put his/her own javascript into some JSON response your site was getting back, that harmful javascript would run on your site, potentially wreaking havoc on your site and embarrassing you. (You shouldn't use eval(jsonString)
for the same reason.)
Secondly, the javascript would create a global variable (at least in this case) and would not be executed in the same scope as the currently running function.
Not to mention the unnecessary expense of creating a new script
element and inserting it into the DOM every time you want to parse some JSON.
The way you are doing it now is great because 1) if there is harmful javascript in your JSON string, it will cause a parse error (JSON only holds data, and can't execute commands) and 2) it keeps everything in the current scope.
精彩评论