简体   繁体   English

如何在JavaScript中引用本地文件?

[英]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. 我在WebStorm中工作,并且尝试使用JavaScript读取文本文件( file.txt )。 I have tried doing this with Ajax, XMLHttpRequest and fetch but all of them returned an 404 error message. 我尝试使用Ajax,XMLHttpRequest和fetch进行此操作,但是它们全部返回了404错误消息。

This is my directory hierarchy: 这是我的目录层次结构:

目录层次结构

NOTE: I am referring the file from artikels.js with the following code: 注意:我使用以下代码从artikels.js引用文件:

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 ... 我犯的错误是,我尝试使用Location.pathname方法(从ibrahim tanyalcin获得建议)后,从artikels.js文件开始构建了file.txt的路径……我发现当前位置是具有到artikels.js文件的“链接”而不是artikels.js位置的HTML页面的位置...

For illustration: 例如:

在此处输入图片说明

The only absolute URL known to XMLHttpRequest() is URL of the document where this script runs. XMLHttpRequest()唯一已知的绝对URL是运行该脚本的文档的URL。

So if you want to use relative URLs they should be relative to your document's URL . 因此,如果要使用相对URL,则它们应相对于文档的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: 或者,如果资产文件夹始终位于站点的根目录,则可以使用根目录相对URL:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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