I have a dynamically generated page where I want to use a static JavaScript and pass it a JSON string as a parameter. I have seen this approach used by Google (see Google’s +1 Button: How do they do it?).
But how should I read the JSON string from the JavaScript?
<html>
<head>
<script src="jquery-1.6.2.min.js"></script>
<script src="myscript.js">{"org": 10, "items":["one","two"]}</script>
</head>
<body>
Hello
</body>
</html>
In this JavaScript I would like to use the JSON argument {"org": 10, "items":["one","two"]} from the HTML document. I don’t know if it’s best to do it with jQuery or without.
$(function() {
// read JSON
alert("the json is:")
})
I would change the script declaration to this:
Note type and id fields. After that
will work just fine in all browsers.
The
type="application/json"is needed to prevent browser from parsing it while loading.And the reason why we use
textContentinstead ofinnerHTMLorinnerTextto read the raw Json text is becauseinnerHTMLtries to parse the contents as HTML which will lead to slower performance and possible parsing bugs and XSS attacks, andinnerTextwon’t grab the raw text and will instead look for human-visible text, whereastextContentgrabs the pure text as-is (which is what you want). See https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent for more details about whyinnerHTMLandinnerTextare bad.