如何在 JavaScript 中读取外部本地 JSON 文件? [英] How to read an external local JSON file in JavaScript?
问题描述
我在本地系统中保存了一个 JSON 文件并创建了一个 JavaScript 文件,以便读取 JSON 文件并打印出数据.这是 JSON 文件:
I have saved a JSON file in my local system and created a JavaScript file in order to read the JSON file and print data out. Here is the JSON file:
{"resource":"A","literals":["B","C","D"]}
假设这是 JSON 文件的路径:/Users/Documents/workspace/test.json
.
Let’s say this is the path of the JSON file: /Users/Documents/workspace/test.json
.
谁能帮我写一段简单的代码来读取 JSON 文件并用 JavaScript 打印数据?
Could anyone please help me write a simple piece of code to read the JSON file and print the data in JavaScript?
推荐答案
您不能对本地资源进行 AJAX 调用,因为请求是使用 HTTP 发出的.
You cannot make a AJAX call to a local resource as the request is made using HTTP.
一种解决方法是运行本地网络服务器,提供文件并对本地主机进行 AJAX 调用.
A workaround is to run a local webserver, serve up the file and make the AJAX call to localhost.
在帮助你编写代码读取 JSON 方面,你应该阅读 jQuery.getJSON()
的文档:
In terms of helping you write code to read JSON, you should read the documentation for jQuery.getJSON()
:
http://api.jquery.com/jQuery.getJSON/
这篇关于如何在 JavaScript 中读取外部本地 JSON 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!