简体   繁体   English

如何读取本地json文件?

[英]How to read a local json file?

I have seen similar questions here but I just can't understand them. 我在这里看到过类似的问题,但我无法理解它们。

I am building a small web page and I want to read a .json file from my file system and get the object in it. 我正在构建一个小网页,我想从我的文件系统中读取一个.json文件并获取其中的对象。

The web page is also local and the .json file is in the same folder as the .html file. 该网页也是本地的,.json文件与.html文件位于同一文件夹中。

How to do that on my Ubuntu machine without using any servers and without jquery if it is possible? 如果可以的话,如何在不使用任何服务器且没有jquery的情况下在我的Ubuntu机器上执行此操作?

Here's some vanilla javascript XMLHTTPRequest code, which does take into account the IE quirks of ActiveX objects: 这里有一些vanilla javascript XMLHTTPRequest代码,它考虑了ActiveX对象的IE怪癖:

var useActiveX = typeof ActiveXObject !== 'undefined';
function loadJSON(file, callback) {
    var xobj;
    if (useActiveX) {
        xobj = new ActiveXObject('Microsoft.XMLHTTP'); 
    } else {
        xobj = new XMLHttpRequest();
    }
    xobj.callback = callback;
    if (xobj.overrideMimeType) {
        xobj.overrideMimeType('application/json');
    }
    xobj.open('GET', file, false);
    xobj.onreadystatechange = function() {
        if (this.readyState === 4) {
            this.callback(this);
        }
     }
     xobj.send(null);
}

Then you just run it by feeding it a filepath and a callback function: 然后你只需通过提供文件路径和回调函数来运行它:

loadJSON('filename.json', function(obj) {
    alert(obj.responseText);
}

You can simply append a <script> tag to your page, pointing the SRC to the local .js file in the same folder. 您只需将<script>标记附加到页面,将SRC指向同一文件夹中的本地.js文件即可。 You don't need to use Ajax. 您不需要使用Ajax。

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

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