2 回答
TA贡献1773条经验 获得超3个赞
您可以通过XMLHttpRequest从 json 中获取数据
这里有一个示例代码:
let xhr = new XMLHttpRequest();
xhr.open("GET", "petsData.json");
xhr.addEventListener("readystatechange", function () {
// any change in the request will result in calling this function
// here you can check the readyState of the request (4 means DONE)
// we want also the status to be 200 OK
if (xhr.readyState === 4 && xhr.status === 200) {
// here you are sure that the data has been fetched correctly
let response = xhr.response;
/* DO SOMETHING WITH response */
}
});
xhr.send();
TA贡献1802条经验 获得超5个赞
最快和最简单的方法是变通,创建一个 petsData.js 文件:
export default {
petsData: [
{
name: "Purrsloud",
species: "Cat",
favFoods: ["wet food", "dry food", "<strong>any</strong> food"],
birthYear: 2016,
photo: "https://learnwebcode.github.io/json-example/images/cat-2.jpg"
}
}
并在您需要的任何地方导入(如有必要,更新文件路径),如下所示:
import petsData from "./petsData.js";
console.log(petsData.petsData)
添加回答
举报
