How can I read a JSON in the script-tag from JavaScript?

北城以北 提交于 2019-11-26 10:30:04

问题


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

回答1:


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.




回答2:


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);



回答3:


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>



回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!