如何在不浏览的情况下从本地文本文件中获取信息? [英] How can I get information from a local text file without browsing?

查看:57
本文介绍了如何在不浏览的情况下从本地文本文件中获取信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想做的是使用JavaScript从与html文件位于同一目录中的文件中获取文本.我想将一个数组存储在文本文件中,并在需要时进行更改,而不必经常去输入代码,保存它,检查它是否有效等.

我曾尝试环顾四周,但找不到任何明确的信息,我发现的大部分内容是使用 .readAsBinaryString 等.

我主要看到的是这样的东西,但我似乎找不到任何实际上无法从文本文件中获取信息的东西,而无需使该人找到文本文件目录.

 函数storearray(newval){var file =文件位置;"var txt = file.txt;var array = txt.split("|");txt = txt + newval +"|" ;;返回数组;} 

解决方案

要从用户磁盘中读取文件,您需要使用 FileReader ,并且用户必须明确选择使用文件输入的文件.(请参见 JavaScript无需使用输入即可读取文件).

要从网站中读取文件,您需要使用Ajax(具有 fetch XMLHttpRequest 或像Axios一样围绕它们的库).(请参见使用从MDN提取).

如果(如此处所示)您要从网站 读取数据,但是该网站仅存在于用户磁盘上,那么您仍然需要使用Ajax,但通常会遇到 解决方案

To read a file from the user's disk you need to use FileReader and the user must explicitly select the file using a file input. (See JavaScript read file without using input).

To read a a file from the website you need to use Ajax (with fetch, XMLHttpRequest or a library that wraps around them like Axios). (See Using fetch from MDN).

If (as it seems here) you want to read data from the website but the website exists only on the user's disk then you still need to use Ajax but will usually run into security restrictions. Some browsers allow you to disable the security protection, but the general solution is to install a web server and load both HTML and the data file using HTTP.

Alternatively, you can store your data in JavaScript (you are generating an array from your text file, you can so that manually or have a build-time script do it) and just load it with a <script> element.

这篇关于如何在不浏览的情况下从本地文本文件中获取信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆