gpt4 book ai didi

javascript - 在 JavaScript 中使用 .JSON

转载 作者:行者123 更新时间:2023-11-30 08:03:00 25 4
gpt4 key购买 nike

对于我当前的项目,我想用 JavaScript 读取 JSON 文件的值。因为我对他们两个都不熟悉,所以我有点迷路了。使用下面的代码,我的 JavaScript 控制台出现以下错误:

XMLHttpRequest cannot load file:///Users/Fabio/Desktop/SkriptET/files.json. Received an invalid response. Origin 'null' is therefore not allowed access.

文件保存在那里。

index.html

<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
</body>
</html>

文件.json

{
"category":
{
"Gleichstromkreise":
[
{
"title":"Elektrische Ladung Q",
"url":"/elladq.html",
"url_next": "/coulomb.html",
"url_prev": "/index.html"
},
{
"title":"Coulombsches Gesetz",
"url":"/coulomb.html",
"url_next":"/el_spannung.html",
"url_prev":"ellektrische_ladung_q.html"
}
],
"Elektrische Felder":
[
...
]
}
}

javascript.js

$.getJSON( "files.json", function( data ) {
alert(data.category.Gleichstromkreise[0].title);
});

最佳答案

问题不是 JSON,而是 Same Origin Policy .当您的页面是从本地文件而不是通过 HTTP 加载时,那是 origin“null”。一些浏览器阻止 origin null 和 origin null 之间的 ajax 调用,甚至阻止从同一目录加载文件。

如果您通过网络服务器运行它(您可以在本地安装一个用于开发),这些文件将具有相同的来源并且浏览器将允许您加载 JSON 文件。

关于javascript - 在 JavaScript 中使用 .JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23512217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com