简体   繁体   English

JavaScript 获取本地 json 文件

[英]JavaScript fetching local json file

I've got this code set and a json file called statistics.json but when I log the data it says data is not defined我有这个代码集和一个名为 statistics.json 的 json 文件,但是当我记录数据时它说数据未定义

Anyone knows how to solve this?任何人都知道如何解决这个问题?

const showStatistics = function(){
    fetch("../assets/statistics.json")
    .then(res => res.json())
    .then(data => {data.stats})
    .catch(err => console.error(err));

    console.log(data);
}

You need to log data inside callback at then , because it is asynchronous.您需要在then回调中记录data ,因为它是异步的。

const showStatistics = function(){
    fetch("../assets/statistics.json")
    .then(res => res.json())
    .then(data => {
        console.log(data);
    })
    .catch(err => console.error(err));

    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM