我如何阅读< script>内的json内容?标签? [英] How can I read json content inside a <script> tag?

查看:89
本文介绍了我如何阅读< script>内的json内容?标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当我想在网页上放置Google +1按钮时,我会这样做:

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

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

但我想知道,脚本标记中有一个对象,但它也加载了 plusone.js !最后,脚本还可以获取标签内的对象。 Google如何做到这一点?通常情况下,我不会在里面放任何东西。通常我会这样做

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

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


推荐答案

由于URL已知,所以很简单:

Since the URL is known, it's simple enough:

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






也就是说,正如Alohci在评论中指出的那样,该页面上的最后一个脚本将是脚本运行时加载的最后一个脚本,因为(除非另有指定)脚本被阻止。因此,这将工作:


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:

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

这篇关于我如何阅读&lt; script&gt;内的json内容?标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆