如何在标记内读取json内容?

时间:2020-12-07 21:14:50

So when I want to put a Google +1 button on webpages, I would do this:

所以当我想在网页上添加谷歌+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! 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

但是我想知道,脚本标记中有一个对象,但是它也正在加载pluson .js!最后,脚本还可以获取标签内的对象。谷歌是怎么做到的?和往常不同的是,我不会在里面放任何东西。通常我会做

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

1 个解决方案

#1


7  

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. Therefore, this would work:

正如Alohci在评论中指出的,当脚本运行时,页面上的最后一个脚本将是最后一个加载的脚本,因为(除非另有说明)脚本正在阻塞。因此,这将工作:

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

#1


7  

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. Therefore, this would work:

正如Alohci在评论中指出的,当脚本运行时,页面上的最后一个脚本将是最后一个加载的脚本,因为(除非另有说明)脚本正在阻塞。因此,这将工作:

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