简体   繁体   English

将外部本地 JSON 文件读入 Javascript

[英]read an external local JSON file into Javascript

I am learning to read an external local JSON files into javascript.我正在学习将外部本地 JSON 文件读入 javascript。 I follow the link below我按照下面的链接

How to read an external local JSON file in Javascript 如何在 Javascript 中读取外部本地 JSON 文件

However, I am not able to make it.但是,我无法做到。 I have a test.json in my C drive, which path is "c:\\\\test.json".我的 C 盘中有一个 test.json,路径是“c:\\\\test.json”。 I think my program works like this: when the content in the local json file is updated, my program is going to alert the data in the json file.我认为我的程序是这样工作的:当本地 json 文件中的内容更新时,我的程序将提醒 json 文件中的数据。 I don't know what is wrong in my program.我不知道我的程序有什么问题。 Hope someone could help me out.希望有人可以帮助我。 Thank you in advance.提前谢谢你。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>noName</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
    <script type="text/javascript" src="test.json"></script>
    <script type="text/javascript" src="javascrip.js"></script>
</head>


<script type="text/javascript">

    $(document).ready(function() {
        alert("goes here ");
        readTextFile("c:/test.json", function(text){
        var data = JSON.parse(text);
        alert(data);
    });
});


function readTextFile(file, callback) {
     var rawFile = new XMLHttpRequest();
     rawFile.overrideMimeType("application/json");
     rawFile.open("GET", file, true);
     rawFile.onreadystatechange = function() {
         if (rawFile.readyState === 4 && rawFile.status == "200") {
             callback(rawFile.responseText);
         }
     };
     rawFile.send(null);
}

test.json测试文件

{"notes":["s0","s5","s4","s3","s2","s1"]} {"notes":["s0","s5","s4","s3","s2","s1"]}

For learning and testing locally, I highly recommend using Firefox.对于本地学习和测试,我强烈建议使用 Firefox。 It's a great browser to develop with because it's pretty lax with respect to loading local files.这是一个很好的开发浏览器,因为它在加载本地文件方面非常宽松。

For example, it can load local files using xhr no problem.例如,它可以使用 xhr 加载本地文件没问题。

Note that you can't load ANY file off the local system... just files "looking forward" from you HTML page (relative) "foo/bar/data.json", but not "C:/data.json".请注意,您不能从本地系统加载任何文件......只是从您的 HTML 页面(相对)“foo/bar/data.json”“期待”的文件,而不是“C:/data.json”。

Another thing to consider is that the local file system and http are two completely different animals.另一件要考虑的事情是本地文件系统和 http 是两种完全不同的动物。 When a browser makes an "http request" it is assuming a header, response codes, and data will be coming back at it.当浏览器发出“http 请求”时,它假定标头、响应代码和数据将返回给它。 Whereas when loading local files, there's no such thing as a header nor response codes because the "request" is just a system-level message to load raw data.而在加载本地文件时,没有标头或响应代码之类的东西,因为“请求”只是加载原始数据的系统级消息。 One indicator of these differences is how when you drag and drop a file from your system into a browser window, you'll see file:/// vs a web page using http://这些差异的一个指标是,当您将文件从系统拖放到浏览器窗口时,您会看到 file:/// 与使用 http:// 的网页

Hope this helps.希望这会有所帮助。

And one last thing.还有最后一件事。 When you use the overrideMimeType("application/json"), you're asking the browser to parse the resulting response as json, not text.当您使用 overrideMimeType("application/json") 时,您是在要求浏览器将结果响应解析为 json,而不是文本。 So you may want to try returning just the response?所以你可能想尝试只返回响应?

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
       if (rawFile.readyState === 4 && rawFile.status == "200") {
           // callback(rawFile.responseText);
           callback(rawFile.response);
       }
    };
    rawFile.send(null);
}

That way you shouldn't have to parse the JSON later?这样你以后就不必解析 JSON 了吗?

Alternatively, don't over-ride response, and handle JSON parsing like you're doing.或者,不要覆盖响应,并像您一样处理 JSON 解析。

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    //rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
       if (rawFile.readyState === 4 && rawFile.status == "200") {
           callback(rawFile.responseText);
       }
    };
    rawFile.send(null);
}

You can't access the local file via Ajax.您无法通过 Ajax 访问本地文件。 Browser definition this is not safe to operate.浏览器定义这是不安全的操作。

Using AngularJS: $http service使用 AngularJS:$http 服务

$http.get(url)
.then(function(response) {
  // Use the response Json data
});

Using jQuery:使用jQuery:

$.getJSON(url, function(result){
    //use result Json data
});

Where URL will be path to your local json file.其中 URL 将是本地 json 文件的路径。

Loading local files is strictly forbidden in javascript. javascript 中严禁加载本地文件。 It is one of the flaws of this language.这是这种语言的缺陷之一。 However, json is already a javascript object, the content of JSON file can be read inside script tag.但是,json 已经是一个 javascript 对象,可以在 script 标签内读取 JSON 文件的内容。

The question is how do you make the json file, because it is easier to store it in a variable for you to refer to that variable once you include it script tag.问题是如何制作 json 文件,因为将它存储在变量中更容易,以便您在包含脚本标记后引用该变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM