简体   繁体   中英

How to refer to a local file in JavaScript?

I am working in WebStorm and I am trying to read a text file ( file.txt ) with JavaScript. I have tried doing this with Ajax, XMLHttpRequest and fetch but all of them returned an 404 error message.

This is my directory hierarchy:

目录层次结构

NOTE: I am referring the file from artikels.js with the following code:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'data/file.txt', false);
xhr.onload = function() {
  if (this.status == 0) {
      const resp = this.response;
      console.log(resp);
  } else {
      console.log("fail");
}};
xhr.send();

I have been trying to alter the link to the following forms:

assets/js/own/data/file.txt
/assets/js/own/data/file.txt
./data/file.txt

How should I write the link in order to make it work?

SOLVED:

The mistake I made was that I build the path to the file.txt starting from the artikels.js file ... after trying the Location.pathname method (thanks to ibrahim tanyalcin for the advice) I found out that the current location was the location of the HTML-page that had a 'link' to the artikels.js file and not the artikels.js location ...

For illustration:

在此处输入图片说明

The only absolute URL known to XMLHttpRequest() is URL of the document where this script runs.

So if you want to use relative URLs they should be relative to your document's URL .

Thus:

xhr.open('GET', 'assets/js/own/data/file.txt', false); 

Or you can use root relative URLs if assets folder is always at the root of your site:

xhr.open('GET', '/assets/js/own/data/file.txt', false); 

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