[英]Load data from local JSON file into javascript
[added:] Thank you guys for the reply. [添加:]谢谢你们的答复。 I understand that ajax has to used on a server.
我了解ajax必须在服务器上使用。 I wonder if there is a way to load the data from local json file into js in this example?
我想知道在此示例中是否有办法将本地json文件中的数据加载到js中?
I have a file named employee.json
. 我有一个名为
employee.json
的文件。 I tried load this JSON data into JavaScript. 我尝试将此JSON数据加载到JavaScript中。 I saved both the .json and .html files on my desktop but when I click in the HTML, there is nothing shown.
我将.json和.html文件都保存在桌面上,但是当我单击HTML时,没有显示任何内容。 I tried to use
alert()
in the .ajax()
method but it does not work. 我试图在
.ajax()
方法中使用alert()
,但是它不起作用。 I am not sure what is wrong with my AJAX method. 我不确定我的AJAX方法有什么问题。 What do I need to do to take the
id
from the JSON and put it into an array in javaScript? 我需要怎么做才能从JSON中获取
id
并将其放入JavaScript中的数组中? Thank you in advance. 先感谢您。
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
method: 'get',
cache: false,
success: function(data) {
$(data.employee).each(function(index, value) {
res.push(value.id);
});
document.getElementById("demo").innerHTML = res.toString();
}
});
</script>
</body>
</html>
{
"employee": [{
"id" : 1,
"firstName" : "Lokesh"
},{
"id" : 2,
"firstName" : "bryant"
},{
"id" : 3,
"firstName" : "kobe"
}]
}
As an alternative you can load your JSON as a javascript, just wrap all your JSON data into 或者,您可以将JSON作为JavaScript加载,只需将所有JSON数据包装到
var employees = { /*all your json data here*/ }
and save this as employees.js 并将其保存为employees.js
Then you can just use a regular script tag in the html: 然后,您可以在html中使用常规脚本标签:
<script src="/yourpath/employees.js"/>
And then inside your javascript "employees" will be a global object. 然后在您的javascript“员工”内部将是一个全局对象。 so you will have:
因此您将拥有:
employess.employee[1].FirstName
result in "bryant" in your case; 在您的情况下导致“ bryant”;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.