[英]How to get JSON data from JSON file
我需要做一个小程序。 这个小程序是一个备用提醒。 我使用JSON文件。 我需要做一个下拉菜单,所以我在JSON文件中做了以下代码:
`"questions": [
{
"key": "reminder",
"label": "Choose the time",
"help": "You can find the stock ticker on the web",
"required": true,
"order": 1,
"controlType": "dropdown",
"options":[10, 15, 20, 30, 40, 50, 60]
}
],`
这些选项是一个列表,以便允许用户在需要警报时进行选择。 但是我需要像在我的JS文件中的条目一样接受这些选项,以便在以后用一个函数倒计时。 您能帮我找到如何输入条目等options
并将其显示为JS文件吗?
您可以使用fetch
获取JSON文件。
fetch("../yourFile.JSON").then(res => res.json()).then(data => {
//do something with your JSON
});
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(res => res.json()).then(json => { console.log(json); });
较新的浏览器支持XMLHttpRequest对象的responseType
属性,您可以将其设置为“ json”,然后获取带有XMLHttpRequest的response属性的JSON响应。
注意:IE11不支持responseType='json'
var req = new XMLHttpRequest;
req.responseType = 'json';
req.open('GET', "../yourFile.JSON", true);
req.onload = function() {
var json = req.response;
// do something with your JSON
};
req.send(null);
var req = new XMLHttpRequest; req.responseType = 'json'; req.open('GET', "https://jsonplaceholder.typicode.com/todos/1", true); req.onload = function() { var json = req.response; console.log(json); // do something with your JSON }; req.send(null);
为了支持较旧的浏览器,可以使用XMLHttpRequest和JSON.parse
将responseText转换为JSON。
var req = new XMLHttpRequest;
req.overrideMimeType("application/json");
req.open('GET', "../yourFile.JSON", true);
req.onload = function() {
var json = JSON.parse(req.responseText);
//do something with your JSON
};
req.send(null);
var req = new XMLHttpRequest; req.overrideMimeType("application/json"); req.open('GET', "https://jsonplaceholder.typicode.com/todos/1", true); req.onload = function() { var json = JSON.parse(req.responseText); console.log(json); //do something with your JSON }; req.send(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.