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:
<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').innerHTML);
will work just fine in all browsers.
The type="application/json"
is needed to prevent browser from parsing it while loading.
I ended up with this JavaScript code to be independent of jQuery.
var json = document.getElementsByTagName('script');
var myObject = JSON.parse(json[json.length-1].textContent);
To read JSON in <script id="myJSON">
use
var manifest= document.getElementById('myJSON').innerHTML; //sets manifest to the text in #myJSON
manifest= JSON.parse(manifest) //Converts text into JSON
You can also use methods to point to the script like document.scripts[0]
//var manifest= JSON.parse(document.getElementById('myJSON').innerHTML); /*Shortend of 2&3*/
var manifest= document.getElementById('myJSON').innerHTML; //Gets text in #myJSON
manifest= JSON.parse(manifest) //Converts it into JSON
document.getElementById('test').innerHTML= manifest.name+ '<br/>'+ manifest.otherOptions; //Displays it
console.log('manifest')
console.log(manifest);
<head>
<script type="application/json" id="myJSON">
{"name":"Web Starter Kit", "otherOptions":"directly here"}
</script>
</head>
<body>
<p id="test"></p>
</body>
JSON.parse($('script[src="mysript.js"]').html());
or invent some other method to identify the script.
Maybe instead of .html()
you might need .text()
. Not sure. Try them both.
来源:https://stackoverflow.com/questions/7581133/how-can-i-read-a-json-in-the-script-tag-from-javascript