尝试加载本地 JSON 文件以使用 JQuery 在 html 页面中显示数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18637418/
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
Trying to load local JSON file to show data in a html page using JQuery
提问by Venkata Krishna
Hi I am trying to load local JSON file using JQuery to show data but i am getting some weird error. May i know how to solve this.
嗨,我正在尝试使用 JQuery 加载本地 JSON 文件以显示数据,但出现了一些奇怪的错误。我可以知道如何解决这个问题。
<html>
<head>
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$.getJSON( "priorities.json" , function( result ){
alert(result.start.count);
});
});
</script></head>
</html>
I am just alerting the count of JSON data. My JSON file is in the same directory where this html file is and JSON string format is shown below.
我只是提醒 JSON 数据的数量。我的 JSON 文件位于此 html 文件所在的同一目录中,JSON 字符串格式如下所示。
{
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
}
JSON file name priorities.json and error is
JSON 文件名优先级.json 和错误是
Uncaught Referenceerror priorities is not defined
未定义未捕获的 Referenceerror 优先级
采纳答案by hequ
As the jQuery API says: "Load JSON-encoded data from the server using a GET HTTP request."
正如 jQuery API 所说:“使用 GET HTTP 请求从服务器加载 JSON 编码的数据。”
http://api.jquery.com/jQuery.getJSON/
http://api.jquery.com/jQuery.getJSON/
So you cannot load a local file with that function. But as you browse the web then you will see that loading a file from filesystem is really difficult in javascript as the following thread says:
因此,您无法使用该功能加载本地文件。但是当您浏览网页时,您会发现在 javascript 中从文件系统加载文件真的很困难,如下面的帖子所述:
回答by Khanh TO
Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.
由于安全问题(同源策略),如果没有用户交互,javascript 对本地文件的访问将受到限制。
According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:
根据https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:
A file can read another file only if the parent directory of the originating file is an ancestor directory of the target file.
只有当原始文件的父目录是目标文件的祖先目录时,文件才能读取另一个文件。
Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:
想象一下这样一种情况:来自网站的 javascript 试图在您不知道的情况下窃取您系统中任何位置的文件。您必须将其部署到 Web 服务器。或者尝试使用脚本标签加载它。像这样:
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" language="javascript" src="priorities.json"></script>
<script type="text/javascript">
$(document).ready(function(e) {
alert(jsonObject.start.count);
});
</script>
Your priorities.json file:
您的 priority.json 文件:
var jsonObject = {
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
}
Or declare a callback function on your page and wrap it like jsonp technique:
或者在您的页面上声明一个回调函数并像 jsonp 技术一样包装它:
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(e) {
});
function jsonCallback(jsonObject){
alert(jsonObject.start.count);
}
</script>
<script type="text/javascript" language="javascript" src="priorities.json"></script>
Your priorities.json file:
您的 priority.json 文件:
jsonCallback({
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
})
Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.
使用脚本标签是一种与 JSONP 类似的技术,但这种方法不太灵活。我建议将其部署在 Web 服务器上。
With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the userfrom <input type="file"/>
or dropped from the desktop to the browser.
通过用户交互,允许 javascript 访问文件。这就是File API的情况。使用文件 api,javascript 可以访问用户从<input type="file"/>
桌面选择或从桌面拖放到浏览器的文件。
回答by senornestor
You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees
, for example.
您可以简单地在 HTML 中包含一个 Javascript 文件,该文件将您的 JSON 对象声明为变量。然后,您可以使用data.employees
例如从全局 Javascript 范围访问您的 JSON 数据。
index.html:
索引.html:
<html>
<head>
</head>
<body>
<script src="data.js"></script>
</body>
</html>
data.js:
数据.js:
var data = {
"start": {
"count": "5",
"title": "start",
"priorities": [{
"txt": "Work"
}, {
"txt": "Time Sense"
}, {
"txt": "Dicipline"
}, {
"txt": "Confidence"
}, {
"txt": "CrossFunctional"
}]
}
}
回答by Surya Singh
app.js
应用程序.js
$("button").click( function() {
$.getJSON( "article.json", function(obj) {
$.each(obj, function(key, value) {
$("ul").append("<li>"+value.name+"'s age is : "+value.age+"</li>");
});
});
});
index.html
索引.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tax Calulator</title>
<script src="jquery-3.2.0.min.js" type="text/javascript"></script>
</head>
<body>
<ul></ul>
<button>Users</button>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
article.json
文章.json
{
"a": {
"name": "Abra",
"age": 125,
"company": "Dabra"
},
"b": {
"name": "Tudak tudak",
"age": 228,
"company": "Dhidak dhidak"
}
}
server.js
服务器.js
var http = require('http');
var fs = require('fs');
function onRequest(request,response){
if(request.method == 'GET' && request.url == '/') {
response.writeHead(200,{"Content-Type":"text/html"});
fs.createReadStream("./index.html").pipe(response);
} else if(request.method == 'GET' && request.url == '/jquery-3.2.0.min.js') {
response.writeHead(200,{"Content-Type":"text/javascript"});
fs.createReadStream("./jquery-3.2.0.min.js").pipe(response);
} else if(request.method == 'GET' && request.url == '/app.js') {
response.writeHead(200,{"Content-Type":"text/javascript"});
fs.createReadStream("./app.js").pipe(response);
}
else if(request.method == 'GET' && request.url == '/article.json') {
response.writeHead(200,{"Content-Type":"text/json"});
fs.createReadStream("./article.json").pipe(response);
}
}
http.createServer(onRequest).listen(2341);
console.log("Server is running ....");
Server.js will run a simple node http server in your local to process the data.
Server.js 将在您的本地运行一个简单的节点 http 服务器来处理数据。
Notedon't forget toa dd jQuery library in your folder structure and change the version number accordingly in server.jsand index.html
注意不要忘记在文件夹结构中添加一个 dd jQuery 库,并相应地在server.js和index.html 中更改版本号
This is my running one https://github.com/surya4/jquery-json.
这是我正在运行的一个https://github.com/surya4/jquery-json。
回答by Nikhil VJ
The d3.js visualization examples I've been replicating on my local machine.. which import .JSON data.. all work fine on Mozilla Firefox browser; and on Chrome I get the cross-origins restrictions error. It's a weird thing how there's no issue with importing a local javascript file, but try loading a JSON and the browser gets nervous. There should at least be some setting to let the user over-ride it, the way pop-ups are blocked but I get to see an indication and a choice to unblock them.. no reason to be so Orwellian about the matter. Users shouldn't be treated as too naive to know what's best for them.
我一直在本地机器上复制的 d3.js 可视化示例……它们导入了 .JSON 数据……在 Mozilla Firefox 浏览器上一切正常;在 Chrome 上,我收到了跨域限制错误。很奇怪,导入本地 javascript 文件没有问题,但是尝试加载 JSON 并且浏览器变得紧张。至少应该有一些设置让用户超越它,弹出窗口被阻止的方式,但我看到了一个指示和一个解除阻止它们的选择......没有理由对此事如此奥威尔式。用户不应被视为太天真而无法知道什么对他们最有利。
So I suggest using Firefox browser if you're working locally. And I hope people don't freak out over this and start bombing Mozilla to enforce cross-origin restrictions for local files.
因此,如果您在本地工作,我建议您使用 Firefox 浏览器。我希望人们不要为此感到害怕并开始轰炸 Mozilla 以强制执行本地文件的跨域限制。
回答by Hamza Ahmed Jameel
I have Used Following Methods But non of them worked:
我使用了以下方法,但没有一个有效:
// 2 Method Failed
$.get(
'http://www.corsproxy.com/' +
'en.github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
function (response) {
console.log("> ", response);
$("#viewer").html(response);
});
// 3 Method Failed
var jqxhr = $.getJSON( "./json/movies-coming-soon.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
console.log( "second complete" );
});
// 4 Method Failed
$.ajax({
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
success: function(jsondata){
console.log(jsondata)
}
})
// 5 Method Failed
$.ajax({
url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
headers: { 'Access-Control-Allow-Origin': 'htt://site allowed to access' },
dataType: 'jsonp',
/* etc */
success: function(jsondata){
}
})
What worked For me to simply download chrome extension called "200 OK!" or Web server for chrome and write my code like this:
什么对我来说只是下载名为“200 OK!”的chrome扩展程序。或 chrome 的 Web 服务器并像这样编写我的代码:
// Worked After local Web Server
$(document).ready(function () {
$.getJSON('./json/movies-coming-soon.json', function (data) {
var movie_name = '';
var movie_year = '';
$.each(data,function(i,item){
console.log(item.title,item.year,item.poster)
movie_name += item.title + " " + item.year + "<br> <br>"
$('#movie_name').html(movie_name)
})
})
})
Its because you can not access local file without running local web server as per CORS policy so in order to running it you must have some host server.
这是因为您无法根据 CORS 策略在不运行本地 Web 服务器的情况下访问本地文件,因此为了运行它,您必须拥有一些主机服务器。
回答by amir
I would try to save my object as .txt file and then fetch it like this:
我会尝试将我的对象保存为 .txt 文件,然后像这样获取它:
$.get('yourJsonFileAsString.txt', function(data) {
console.log( $.parseJSON( data ) );
});