简体   繁体   English

如何从txt文件获取对象以在javascript数组中使用?

[英]How to get objects from txt file to use in javascript array?

I am very new to coding and javascript; 我对编码和JavaScript非常陌生; just a few days in. I was wondering if there was a way to import objects from a text file(separated by lines) to use in my array: replyText . 短短几天之后。我想知道是否有一种方法可以从文本文件(由行分隔)中导入对象,以便在我的数组中使用: replyText Here is what I'm working with: 这是我正在使用的:

// Variables

var theButton = document.getElementById("theButton");
var mainText = document.getElementById("mainText");
var replyText = [...,...,...,...,];
var i = 0;

// Functions

function nextText() {
  mainText.innerHTML = replyText[i++ % replyText.length];
}

// MAIN SCRIPT

theButton.onclick = function() {
    nextText();
};

You can use XMLHttpRequest to get the .txt file just pass the path of it. 您可以使用XMLHttpRequest来获取.txt文件,只需传递它的路径即可。

var file = new XMLHttpRequest();
file.open("GET", "file:/../file.txt", false);
file.onreadystatechange = function () {
    if (file.readyState === 4) {
        if (file.status === 200 || file.status == 0) {
            var text = file.responseText;
            alert(text);
        }
    }
}

EDIT: you must pass the absolute path file:///C:/your/path/to/file.txt 编辑:您必须传递绝对路径file:///C:/your/path/to/file.txt

For client/browser-side file reading: 对于客户端/浏览器端文件读取:

You cannot easily read a file on the client-side as you are not allowed direct access to the client's file system. 您不能轻易在客户端读取文件,因为不允许直接访问客户端的文件系统。 However, you can place a input element of file type in your HTML markup via which the client can load a file for your program to process. 但是,您可以在HTML标记中放置文件类型的input元素,客户端可以通过该元素来加载文件以供程序处理。 For example: 例如:

<input type="file" id="file" onchange="readFile()" />

Now when the client selects a file for use, the readFile() function will be called which will read and process the file. 现在,当客户端选择要使用的文件时,将调用readFile()函数来读取和处理该文件。 Here's an example: 这是一个例子:

function readFile() {

    var file = document.getElementById('file').files[0]; // select the input element from the DOM

    var fileReader = new FileReader(); // initialize a new File Reader object

    fileReader.onload(function() { // call this function when file is loaded

        console.log(this.result); // <--- You can access the file data from this variable

        // Do necessary processing on the file

    });

    fileReader.readAsText(file); // Read the file as text

}

For more information on File Reader, check out the docs . 有关文件阅读器的更多信息,请查阅docs

要添加Paulo的解决方案,请阅读以下内容,以换行符分隔字符串(换行符)

var replyText = text.split("\n"); // "\n" is new line character

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

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