繁体   English   中英

我们如何在没有任何服务器的情况下读取html页面中的本地Json文件

[英]How can we Read a local Json file in a html page without any server

我想从HTML页面读取本地Json文件。 但是我无法读取适用于chrome和IE的HTML页面中的本地Json文件。 有没有不用任何Web服务器就能做到的任何方法。

假设您在同一文件夹中有index.html和sample.json,可以执行此操作,

$http.get('sample.json').then(function(response) {
    console.log(response);
 });

当然,您将需要从控制器,单独运行或在指令中运行它。

我在网上找到了此解决方案,但我没有尝试过,但根据评论它应该可以工作

function loadJSON(callback) {   

    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
          }
    };
    xobj.send(null);  
 }

The function above will create a new instance of a XMLHttpRequest and load asynchronously the contents of my_data.json. I have gone with asynchronous but you can change the argument to false if you want a synchronous load. Thankfully all modern browsers support the native JSON.parse method. Remember our anonymous callback? here's how you use it.

function init() {
 loadJSON(function(response) {
  // Parse JSON string into object
    var actual_JSON = JSON.parse(response);
 });
}``

http://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript

在转换文件夹中创建一个名为sample.json的JSON文件,然后控制器中的代码使用以下代码获取JSON文件中的值

$http.get('translation/sample.json').success(function(response){
      console.log(response);           
});

要么

$.getJSON('translation/sample.json', function(data){
    console.log(data); 
});

暂无
暂无

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

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