简体   繁体   中英

How do I fetch relative to a JavaScript file

I have a file tree:

index.html

  | js
  |
  | data.json
  | script.js

index.html is just script.js

script.js :

(async function() {
  var req = await fetch("data.json");
  var json = await req.json();
  ...
})();

I'm trying to access data.json from script.js ( js folder) instead of index.html .

So I can't just use js/script.js

How would I do this?

Apparently you can get a path to the currently running script (if it's not ESM), using document.currentScript

Untested, but this would suggest you can build the path like this:

const dataUrl = new URL('data.json', document.currentScript.src);
const req = await fetch(dataUrl);
// etc

Even though the data.json is in the same folder as script.js , since both these files are inside the js folder relative to index.html you would have to use

  var req = await fetch("js/data.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