gpt4 book ai didi

javascript - 我需要从函数外部访问 JSON 数据

转载 作者:行者123 更新时间:2023-11-28 17:04:03 25 4
gpt4 key购买 nike

我打过电话,但没找到。我有一个 JavaScript 文件。我有一个与该文件分开的名为 data.json 的文件。

<小时/>

data.json

{
"today": [
{
"id": 1,
"title": "Note 1",
"date": "21.05.2019",
"text": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Reiciendis, optio, odit, omnis veritatis illum quo doloribus hic inventore vitae adipisci dolorem ducimus natus nostrum recusandae quis assumenda! Vel, reiciendis ipsam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Reiciendis, optio, odit, omnis veritatis illum quo doloribus hic inventore vitae adipisci dolorem ducimus natus nostrum recusandae quis assumenda! Vel, reiciendis ipsam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Reiciendis, optio, odit, omnis veritatis illum quo doloribus hic inventore vitae adipisci dolorem ducimus natus nostrum recusandae quis assumenda! Vel, reiciendis ipsam."
}
]
}

我需要访问 data.json 文件内的数据。但它必须无法正常工作。

示例:

ma​​in.js

let readingTab = document.createElement("div");
readingTab.innerHTML = // json

最佳答案

您可以使用 ES7 的 async/awaitfetch()data.json 文件中获取数据,如下所示:

const getData = async url => { // declare as async so we can use await
const response = await fetch(url); // get response
if(!response.ok) // check if response "worked" (no 404 errors etc...)
throw Error("HTTP Error: " +response.status);

const result = await response.json(); // get JSON from the response
const readingTab = document.createElement("div");
readingTab.textContent = result.today[0].text; // add text to div from retrieved JSON

}
getData('path/to/data.json');

关于javascript - 我需要从函数外部访问 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56414702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com