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

时间:2019-06-02 11:47:39

标签: javascript jquery json

我打电话了,但是找不到。我有一个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文件中的数据。但是它必须无法正常工作。

示例:

main.js

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

2 个答案:

答案 0 :(得分:3)

您可以将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');

答案 1 :(得分:2)

您可以使用HTTP请求来获取JSON文件。 data.json文件的路径应与编写此代码的文件的路径相同。

dataLoader.then(data=> {

});

export const dataLoader = new Promise<any>((resolve, reject) => {
  var xmlhttp = new XMLHttpRequest(),
    method = 'GET',
    url = 'data.json';
    xmlhttp.open(method, url, true);
    xmlhttp.onload = function() {
      if (xmlhttp.status === 200) {
        resolve(JSON.parse(xmlhttp.responseText));
      }
    };
  xmlhttp.send();
});