[英]Read local JSON file using Javascript
I am trying to write a code to read local JSON file in Javascript. 我正在尝试编写代码以使用Javascript读取本地JSON文件。 The code I have written is given below:
我写的代码如下:
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'file:///C:/tmp/abc.json', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
// .open will NOT return a value but simply returns undefined in async mode so use a callback
callback(xobj.responseText);
}
}
xobj.send(null);
Also, I am running Chrome browser using below command: 另外,我正在使用以下命令运行Chrome浏览器:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C://Chrome dev session" --disable-web-security --allow-file-access-from-files
The code isn't working and I am receiving xobj.status
as 0
. 代码无法正常工作,我收到的
xobj.status
为0
。 I have inspected Network tab and found out that xhr
status for abc.json
is shown in red as 'canceled'
. 我检查了网络选项卡,发现
abc.json
xhr
状态以红色显示为'canceled'
。
Please let me know if I am mistaking anything. 如果我有误,请告诉我。
The XMLHttpRequest will fetch resources from a server. XMLHttpRequest将从服务器获取资源。
Your path 你的路
'file:///C:/tmp/abc.json'
is not a url which is being served by a server 不是服务器正在提供的网址
Moreover, with JavaScript you cannot have access to the operating system's storage drive. 此外,使用JavaScript,您将无法访问操作系统的存储驱动器。
To read a local file, you need to use a file uploader and read the contents of the uploaded file via the File API. 要读取本地文件,您需要使用文件上传器,并通过File API读取上载文件的内容。
Try this 尝试这个
https://www.html5rocks.com/en/tutorials/file/dndfiles/ https://www.html5rocks.com/zh-CN/tutorials/file/dndfiles/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.