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: