Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
71
rated 0 times [  74] [ 3]  / answers: 1 / hits: 125931  / 13 Years ago, wed, september 28, 2011, 12:00:00

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:)
})

More From » json

 Answers
35

I would change the script declaration to this:


<script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script>

Note type and id fields. After that


var data = JSON.parse(document.getElementById('data').textContent);

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 textContent instead of innerHTML or innerText to read the raw Json text is because innerHTML tries to parse the contents as HTML which will lead to slower performance and possible parsing bugs and XSS attacks, and innerText won't grab the raw text and will instead look for human-visible text, whereas textContent grabs 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 why innerHTML and innerText are bad.


[#89880] Monday, September 26, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micheleb

Total Points: 275
Total Questions: 103
Total Answers: 103

Location: Macau
Member since Sat, Jul 11, 2020
4 Years ago
;