如何将json文件内容加载到变量

时间:2017-01-14 11:52:16

标签: javascript angularjs json

我的文件系统中有json文件。有没有办法将内容加载到变量?

我试过了:

vm.timeZones = require("timezones.json");

但它会出现此错误:

ReferenceError: require is not defined

3 个答案:

答案 0 :(得分:2)

jQuery.getJSON()应该有所帮助。

参考链接:JQuery.getJSON

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});


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);  
}

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

答案 1 :(得分:0)

可能不是。

如果您是通过HTTP而不是直接从文件系统读取数据,那么您可以使用XMLHttpRequest对象(或者,在较新的浏览器中,获取)Angular摘要通过$http

如果您使用的是Firefox,则可以使用该方法读取与HTML文档位于同一目录(或其子目录)中的本地文件。其他浏览器有更严格的安全规则。

如果您允许用户选择文件(通过<input type="file">),那么您可以使用FileReader API。

答案 2 :(得分:0)

$http.get("timeZones.json")
  .then(function onSuccess(response) {
    // Handle success
    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;         
    //...
    vm.timeZones = data;
  })
  .catch(function onError(response) {
    // Handle error
    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;
    //...
  });

有关详细信息,请参阅AngularJS $http Service API Reference

相关问题