将本地JSON文件中的数据加载到javascript中

时间:2022-07-05 17:03:11

[added:] Thank you guys for the reply. I understand that ajax has to used on a server. I wonder if there is a way to load the data from local json file into js in this example?

[补充说:]谢谢各位回复。我知道ajax必须在服务器上使用。我想知道在这个例子中是否有办法将本地json文件中的数据加载到js中?


I have a file named employee.json. I tried load this JSON data into JavaScript. I saved both the .json and .html files on my desktop but when I click in the HTML, there is nothing shown. I tried to use alert() in the .ajax() method but it does not work. I am not sure what is wrong with my AJAX method. What do I need to do to take the id from the JSON and put it into an array in javaScript? Thank you in advance.

我有一个名为employee.json的文件。我尝试将此JSON数据加载到JavaScript中。我在桌面上保存了.json和.html文件但是当我点击HTML时,没有显示任何内容。我试图在.ajax()方法中使用alert()但它不起作用。我不确定我的AJAX方法有什么问题。我需要做什么才能从JSON中获取id并将其放入javaScript中的数组中?先谢谢你。

<!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"
    }]
}

1 个解决方案

#1


0  

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. so you will have:

然后在你的javascript“employees”中将成为一个全局对象。所以你将拥有:

  employess.employee[1].FirstName

result in "bryant" in your case;

在你的情况下导致“bryant”;

#1


0  

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. so you will have:

然后在你的javascript“employees”中将成为一个全局对象。所以你将拥有:

  employess.employee[1].FirstName

result in "bryant" in your case;

在你的情况下导致“bryant”;