HTML/Javascript:如何使用 src 集访问脚本标签中加载的 JSON 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13515141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML/Javascript: how to access JSON data loaded in a script tag with src set
提问by ChuckE
I have this JSON file I generate in the server I want to make accessible on the client as the page is viewable. Basically what I want to achieve is:
我在服务器中生成了这个 JSON 文件,我想让它在客户端上可以访问,因为页面是可见的。基本上我想要实现的是:
I have the following tag declared in my html document:
我在我的 html 文档中声明了以下标签:
<script id="test" type="application/json" src="http://myresources/stuf.json">
The file referred in its source has JSON data. As I've seen, data has been downloaded, just like it happens with the scripts.
其来源中引用的文件具有 JSON 数据。正如我所见,数据已下载,就像脚本中发生的一样。
Now, how do I access it in Javascript? I've tried accessing the script tag, with and without jQuery, using a multitude of methods to try to get my JSON data, but somehow this doesn't work. Getting its innerHTMLwould have worked had the json data been written inline in the script. Which it wasn't and isn't what I'm trying to achieve.
现在,我如何在 Javascript 中访问它?我已经尝试使用 jQuery 和不使用 jQuery 访问脚本标记,使用多种方法来尝试获取我的 JSON 数据,但不知何故这不起作用。innerHTML如果将 json 数据内联写入脚本中,就可以使用它。它不是,也不是我想要实现的目标。
Remote JSON Request after page loads is also not an option, in case you want to suggest that.
如果您想提出建议,则页面加载后的远程 JSON 请求也不是一种选择。
回答by Ben Lesh
You can't load JSON like that, sorry.
你不能像那样加载 JSON,抱歉。
I know you're thinking "why I can't I just use srchere? I've seen stuff like this...":
我知道你在想“为什么我不能src在这里使用?我见过这样的东西......”:
<script id="myJson" type="application/json">
{
name: 'Foo'
}
</script>
<script type="text/javascript">
$(function() {
var x = JSON.parse($('#myJson').html());
alert(x.name); //Foo
});
</script>
... well to put it simply, that was just the script tag being "abused" as a data holder. You can do that with all sorts of data. For example, a lot of templating engines leverage script tags to hold templates.
...简单地说,这只是脚本标签被“滥用”为数据持有者。你可以用各种数据来做到这一点。例如,许多模板引擎利用脚本标签来保存模板。
You have a short list of options to load your JSON from a remote file:
您有一个从远程文件加载 JSON 的简短选项列表:
- Use
$.get('your.json')or some other such AJAX method. - Write a file that sets a global variable to your json. (seems hokey).
- Pull it into an invisible iframe, then scrape the contents of that after it's loaded (I call this "1997 mode")
- Consult a voodoo priest.
- 使用
$.get('your.json')或其他一些这样的 AJAX 方法。 - 编写一个文件,为您的 json 设置一个全局变量。(似乎是胡说八道)。
- 将它拉到一个不可见的 iframe 中,然后在它加载后刮掉它的内容(我称之为“1997 模式”)
- 咨询巫毒教牧师。
Final point:
最后一点:
Remote JSON Request after page loads is also not an option, in case you want to suggest that.
如果您想提出建议,则页面加载后的远程 JSON 请求也不是一种选择。
... that doesn't make sense. The difference between an AJAX request and a request sent by the browser while processing your <script src="">is essentially nothing. They'll both be doing a GET on the resource. HTTP doesn't care if it's done because of a script tag or an AJAX call, and neither will your server.
……没有意义。AJAX 请求和浏览器在处理您的请求时发送的请求之间的区别<script src="">本质上没有区别。他们都会对资源执行 GET 操作。HTTP 不关心它是否因为脚本标记或 AJAX 调用而完成,您的服务器也不会。
回答by Lea Rosema
Another solution would be to make use of a server-side scripting language and to simply include json-data inline. Here's an example that uses PHP:
另一种解决方案是使用服务器端脚本语言并简单地包含 json-data 内联。这是一个使用 PHP 的示例:
<script id="data" type="application/json"><?php include('stuff.json'); ?></script>
<script>
var jsonData = JSON.parse(document.getElementById('data').textContent)
</script>
The above example uses an extra script tag with type application/json. An even simpler solution is to include the JSON directly into the JavaScript:
上面的例子使用了一个额外的 script 标签,类型为application/json。一个更简单的解决方案是将 JSON 直接包含到 JavaScript 中:
<script>var jsonData = <?php include('stuff.json');?>;</script>
The advantage of the solution with the extra tag is that JavaScript code and JSON data are kept separated from each other.
带有额外标签的解决方案的优点是 JavaScript 代码和 JSON 数据彼此分开。
回答by btx9000
It would appear this is not possible, or at least not supported.
看起来这是不可能的,或者至少不支持。
From the HTML5 specification:
从HTML5 规范:
When used to include data blocks(as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, the src attribute must not be specified, and the contents of the script element must conform to the requirements defined for the format used.
当用于包含数据块(与脚本相反)时,数据必须嵌入 inline,必须使用 type 属性给出数据格式,不得指定 src 属性,并且脚本元素的内容必须符合到为使用的格式定义的要求。
回答by kemicofa ghost
While it's not currently possible with the scripttag, it is possible with an iframeif it's from the same domain.
虽然目前无法使用script标签,但iframe如果它来自同一域,则可以使用。
<iframe
id="mySpecialId"
src="/my/link/to/some.json"
onload="(()=>{if(!window.jsonData){window.jsonData={}}try{window.jsonData[this.id]=JSON.parse(this.contentWindow.document.body.textContent.trim())}catch(e){console.warn(e)}this.remove();})();"
onerror="((err)=>console.warn(err))();"
style="display: none;"
></iframe>
To use the above, simply replace the idand srcattribute with what you need. The id(which we'll assume in this situation is equal to mySpecialId) will be used to store the datain window.jsonData["mySpecialId"].
要使用上述内容,只需将idandsrc属性替换为您需要的内容。在id(我们将在这种情况下,假定等于mySpecialId)将被用于存储数据的window.jsonData["mySpecialId"]。
In other words, for every iframe that has an idand uses the onloadscript will have that data synchronouslyloaded into the window.jsonDataobject under the idspecified.
换句话说,对于每个具有id和 使用onload脚本的iframe,都会将该数据同步加载到指定window.jsonData下的对象id中。
I did this for fun and to show that it's "possible' but I do notrecommend that it be used.
我这样做是为了好玩,并表明它是“可能的”,但我不建议使用它。
Here is an alternative that uses a callback instead.
这是使用回调的替代方法。
<script>
function someCallback(data){
/** do something with data */
console.log(data);
}
function jsonOnLoad(callback){
const raw = this.contentWindow.document.body.textContent.trim();
try {
const data = JSON.parse(raw);
/** do something with data */
callback(data);
}catch(e){
console.warn(e.message);
}
this.remove();
}
</script>
<!-- I frame with src pointing to json file on server, onload we apply "this" to have the iframe context, display none as we don't want to show the iframe -->
<iframe src="your/link/to/some.json" onload="jsonOnLoad.apply(this, someCallback)" style="display: none;"></iframe>
Tested in chrome and should work in firefox. Unsure about IE or Safari.
在 chrome 中测试,应该在 Firefox 中工作。不确定 IE 或 Safari。
回答by Karan
I agree with Ben. You cannot load/import the simple JSON file.
我同意本。您无法加载/导入简单的 JSON 文件。
But if you absolutely want to do that and have flexibility to update json file, you can
但是,如果您绝对想这样做并且可以灵活地更新 json 文件,则可以
my-json.js
我的-json.js
var myJSON = {
id: "12ws",
name: "smith"
}
index.html
索引.html
<head>
<script src="my-json.js"></script>
</head>
<body onload="document.getElementById('json-holder').innerHTML = JSON.stringify(myJSON);">
<div id="json-holder"></div>
</body>
回答by Vitaliy Kaplich
If you need to load JSON from another domain:
http://en.wikipedia.org/wiki/JSONP
However be aware of potential XSSI attacks:
https://www.scip.ch/en/?labs.20160414
如果您需要从另一个域加载 JSON:http:
//en.wikipedia.org/wiki/JSONP
但是要注意潜在的 XSSI 攻击:https://www.scip.ch/en/ ?labs.20160414
If it's the same domain so just use Ajax.
如果是同一个域,那么只需使用 Ajax。
回答by L.Grillo
Check this answer: https://stackoverflow.com/a/7346598/1764509
检查这个答案:https: //stackoverflow.com/a/7346598/1764509
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
回答by hossein sedighian
place something like this in your script file json-content.js
在你的脚本文件中放置这样的东西 json-content.js
var mainjson = { your json data}
then call it from script tag
然后从脚本标签调用它
<script src="json-content.js"></script>
then you can use it in next script
然后你可以在下一个脚本中使用它
<script>
console.log(mainjson)
</script>
回答by DominicTurner
Another alternative to use the exact json within javascript. As it is Javascript Object Notation you can just create your object directly with the json notation. If you store this in a .js file you can use the object in your application. This was a useful option for me when I had some static json data that I wanted to cache in a file separately from the rest of my app.
在 javascript 中使用精确 json 的另一种替代方法。由于它是 Javascript 对象表示法,因此您可以直接使用 json 表示法创建对象。如果将其存储在 .js 文件中,则可以在应用程序中使用该对象。当我想将一些静态 json 数据与应用程序的其余部分分开缓存在一个文件中时,这对我来说是一个有用的选择。
//Just hard code json directly within JS
//here I create an object CLC that represents the json!
$scope.CLC = {
"ContentLayouts": [
{
"ContentLayoutID": 1,
"ContentLayoutTitle": "Right",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/right.png",
"ContentLayoutIndex": 0,
"IsDefault": true
},
{
"ContentLayoutID": 2,
"ContentLayoutTitle": "Bottom",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/bottom.png",
"ContentLayoutIndex": 1,
"IsDefault": false
},
{
"ContentLayoutID": 3,
"ContentLayoutTitle": "Top",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/top.png",
"ContentLayoutIndex": 2,
"IsDefault": false
}
]
};

