如何在JavaScript中读取外部本地JSON文件? [英] How to read an external local JSON file in JavaScript?

查看:541
本文介绍了如何在JavaScript中读取外部本地JSON文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在本地系统中保存了一个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, for instance. 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 with writing a simple piece of code to read the JSON file and print the data inside it in JavaScript?

推荐答案

无法进行AJAX调用使用HTTP发出请求到本地资源。

You cannot make a AJAX call to a local resource as the request is made using HTTP.

解决方法是运行本地Web服务器,提供文件并对本地主机进行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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆