我知道这很简单,但是我整天都在梳头,看看为什么这种获取json数据的常规方法根本不起作用?
我们将不胜感激。谢谢。
此处的沙箱:https://codesandbox.io/s/unruffled-wood-0syn4
sortData.js
var myInit = {
method: "GET",
headers: {
"Content-Type": "application/json"
},
mode: "cors",
cache: "default"
};
let myRequest = new Request("./dataset.json", myInit);
fetch(myRequest)
.then(function(response) {
return response.json();
})
.then(data => {
// Work with JSON data here
console.log(data);
})
.catch(err => {
// Do something for an error here
console.log(err);
});
sampledata.json
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
},
"gloss": {
"title": "example glossary 2",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGMLZZZ",
"SortAs": "SGMLZZ",
"GlossTerm": "Standard Generalized Language",
"Acronym": "SGMAL",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markups"
}
}
}
}
}
答案 0 :(得分:3)
传递给您的Request构造函数的路径必须相对于index.html。将其更改为“ ./src/dataset.json”。