简体   繁体   English

通过脚本标记加载JSON文件

[英]Loading a JSON file via a script tag

I've written a small I18n plugin that accepts different languages via json. 我写了一个小的I18n插件,通过json接受不同的语言。 To make usage as simple as possible for the user, I want them to be able to just plop their json package directly in a page's along with the actual script: 为了使用户尽可能简单,我希望他们能够直接在页面中将json包与实际脚本一起打包:

<script id="pop-language_es" type="application/json" src='languages/es.json'></script>
<script src='pop.js'></script>

To keep this plugin as lean as possible, I want to avoid external dependencies like Jquery. 为了使这个插件尽可能精简,我想避免像Jquery这样的外部依赖。 I can retrieve the script tag using pure js: 我可以使用纯js检索脚本标记:

var json = document.getElementById("pop-language_es");

The problem is, this is only the tag, not the actual json. 问题是,这只是标签,而不是实际的json。 Is there a way to retrieve the contents with something like json.content ? 有没有办法用json.content东西检索内容?

There's a similar question here , in which several people recommend using Ajax. 有一个类似的问题在这里 ,其中几个人建议使用Ajax。 That would definitely work in this situation, but wouldn't that result in the client downloading the json twice? 这肯定会在这种情况下起作用,但这不会导致客户端下载json两次吗? (First during the page load, then again during the Ajax call.) If so, I'd hope there's a better option, as these json files can get quite large. (首先在页面加载期间,然后在Ajax调用期间再次。)如果是这样,我希望有更好的选择,因为这些json文件可以变得非常大。

What you can do is set a global variable within your external file: 您可以做的是在外部文件中设置一个全局变量:

window.myJSON = { ... };

Then your other code can access that data via window.myJSON . 然后您的其他代码可以通过window.myJSON访问该数据。

I'm not sure how browsers parse .json files so you may need to change the extension to .js . 我不确定浏览器如何解析.json文件,因此您可能需要将扩展​​名更改为.js

Once you include your javascript file, you are able to access it's content (variable,methods,...) within your main file. 一旦包含了javascript文件,就可以在主文件中访问它的内容(变量,方法......)。 document.getElementById has nothing to do with the contents on it, it is only looking for the DOM element itself, not the file. document.getElementById与其上的内容无关,它只查找DOM元素本身,而不是文件。

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

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