简体   繁体   English

如何读取<script>标记内的json内容?

[英]How can I read json content inside a <script> tag?

So when I want to put a Google +1 button on webpages, I would do this: 因此,当我想在网页上添加Google +1按钮时,我会这样做:

<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
  {lang: 'zh-TW'}
</script>

But I am wondering, there is an object in the script tag, but it is also loading plusone.js ! 但我想知道,脚本标签中有一个对象,但它也加载了plusone.js At the end the script can also get the object inside the tag. 最后,脚本还可以获取标记内的对象。 How does Google do that? 谷歌如何做到这一点? Unlike normally I would not put anything inside. 不像通常我不会把任何东西放进去。 Normally I would do 通常我会这样做

<script type"text/javascript" src="script.js"></script>

Since the URL is known, it's simple enough: 由于URL已知,因此很简单:

JSON.parse(
    document.querySelector("script[src='https://apis.google.com/js/plusone.js']")
        .innerHTML.replace(/^\s+|\s+$/g,'')
);

That said, as Alohci pointed out in the comments, the last script on the page will be the last one loaded when the script runs, because (unless specified otherwise) scripts are blocking. 也就是说,正如Alohci在评论中指出的那样,页面上的最后一个脚本将是脚本运行时加载的最后一个脚本,因为(除非另有说明)脚本是阻塞的。 Therefore, this would work: 因此,这将工作:

var scripts = document.getElementsByTagName('script');
var data = JSON.parse(scripts[scripts.length-1].innerHTML.replace(/^\s+|\s+$/g,''));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM