猿问

在 Javascript 上本地获取 json 数据

我知道这很简单,但我整天都在纠结为什么这种获取 json 数据的传统方法根本不起作用???


一个帮助将不胜感激。谢谢你。


沙盒在这里:https : //codesandbox.io/s/unruffled-wood-0syn4


排序数据.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);

  });

示例数据集.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"

        }

      }

    }

  }

}


侃侃无极
浏览 226回答 1
1回答

慕雪6442864

传递给您的请求构造函数的路径需要相对于您的 index.html。将其更改为“./src/dataset.json”。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答