[英]How to load json file content to variable
我的文件系统中有json文件。 有什么办法可以将内容加载到变量中?
我尝试了这个:
vm.timeZones = require("timezones.json");
但是它给出了这个错误:
ReferenceError: require is not defined
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);
});
}
可能不是。
如果您是通过HTTP而不是直接从文件系统中读取数据,则可以使用Angular通过$http
抽象的XMLHttpRequest对象(或者,在较新的浏览器中是fetch)。
如果使用的是Firefox,则可以使用该方法读取与HTML文档位于同一目录(或其子目录)的本地文件。 其他浏览器具有更严格的安全规则。
如果允许用户(通过<input type="file">
)选择文件,则可以使用FileReader API。
$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服务API参考》 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.