简体   繁体   中英

Read JSON that is in website source in client-side vanilla javascript

I have a simple JSON file sitting in a data folder within the source of my website. In a javascript script I want to read the JSON and update the DOM with the information inside. The file structure of my website is like this

css
design
html
  |____ category.html (this is where the script will be loaded)
js
  |____updateDomScript.js (this is the script that should be loaded)
src
  |____data
          |____jsonFile.json (this is the json that needs to be loaded)

I obviously can't use require() from nodejs because this is on the client side. I don't see how FileReader would work here. All I need to do is read this JSON file from ../src/data/jsonFile.json .

I meant the third answer, you can use fetch statement. If you are confused about fetch then I recommend you look it up online first.

fetch("path/to/file")
  .then(response => response.json())
  .then(json => console.log(json));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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