使用jQuery/Javascript在本地系统中加载JSON文件 [英] Load a JSON file in local system using jQuery/Javascript
问题描述
我是脚本语言的新手.我有一个new.json
文件,我想加载到gary.html
HTML文件中.我不想在服务器上运行gary.html
文件.我想在我的机器上本地运行它.
I am new to scripting languages. I have a new.json
file and I want to load in gary.html
HTML file. I do not want to run gary.html
file on server. I want to run it locally on my machine.
当我的HTML文件使用$.getJSON
加载new.json
文件时,出现黑屏,并且在控制台上检查时出现错误:
When my HTML file loads the new.json
file using $.getJSON
, I get a blank screen and when I checked on console I get the error:
jquery-3.1.0.js:9392 XMLHttpRequest无法加载文件:///C:/Users/Gary/Desktop/new.json.跨源请求仅支持以下协议方案:http,数据,chrome,chrome扩展名,https,chrome-extension-resource.
jquery-3.1.0.js:9392 XMLHttpRequest cannot load file:///C:/Users/Gary/Desktop/new.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.`
这是我的加载代码
function show() {
//read(a)
var myItems;
$.getJSON('new.json', function(data) {
myItems = data.a;
read(myItems)
});
}
当我搜索此错误时,人们建议我在Firefox上运行此文件,或执行此chrome --allow-file-access-from-files
.该文件正在firefox中加载,当我执行chrome --allow-file-access-from-files
时,该文件也将在chrome中加载.
When I googled for this error, people suggest to me run this file on firefox, or execute this chrome --allow-file-access-from-files
. The file is loading in firefox and when I am executing the chrome --allow-file-access-from-files
, the File also loads in chrome.
我主要担心的是,当我将new.json
和gary.html
文件分发给其他人时,其他人可能会也可能没有Firefox或chrome的chrome --allow-file-access-from-files
权限.我只希望用户单击gary.html
,它会加载new.json
文件的数据.
My main concern is that when I distribute the new.json
and gary.html
file to others then others may or may not have firefox or chrome's chrome --allow-file-access-from-files
permission. I just want user to click on gary.html
and it loads the data of new.json
file.
我该如何实现?
推荐答案
如您所见-您无法向本地文件系统发出AJAX请求,因为这是一个巨大的安全问题.唯一的解决方法是让用户在浏览器中手动启用设置(无论如何,这不是一个好主意).如果您不希望这样做,那么您将必须使用中央服务器来处理所有请求.
As you've seen - you can't make AJAX requests to the local filesystem as it's a huge security issue. The only workaround for this is for the user to manually enable settings in their browser (which is not a great idea anyway). If you do not want this then you will have to use a central server for all requests.
另一种选择是通过使用额外的<script />
标签在页面中包含new.json
文件来避免使用AJAX.您还需要将对象分配给文件中的变量,如下所示:
The alternative is to avoid using AJAX by including the new.json
file in the page using an extra <script />
tag. You will also need to assign the object to a variable in the file, something like this:
// new.json
var newJson = {"a": [{"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}]}
然后在gary.html
中:
<head>
<script src="jquery.js"></script>
<script src="new.json"></script>
<script>
$(function() {
newJson.a.forEach(function(item) {
console.log(item.name);
});
})
</script>
</head>
这篇关于使用jQuery/Javascript在本地系统中加载JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!