简体   繁体   English

读取txt文件并放入javascript数组

[英]Read txt file and put into javascript array

I want to know how i could read a txt file and have the contents of it be into array in javascript.我想知道如何读取 txt 文件并将其内容放入 javascript 数组中。

My txt file looks something like this.我的 txt 文件看起来像这样。 [Skin1],[skin2],[skin3],etc... [皮肤1]、[皮肤2]、[皮肤3]等...

I simply want the array contents to be acquired from the txt file instead of writing the array into the actual html file.我只是希望从 txt 文件中获取数组内容,而不是将数组写入实际的 html 文件。

I am fairly new to javascript and do not understand how to do this.我对javascript相当陌生,不明白如何做到这一点。

Ps my html and txt files will be on the same server. Ps 我的 html 和 txt 文件将在同一台服务器上。 If that makes a difference.如果这有所作为。

I would really appreciate an example code, thanks in advance.我真的很感激示例代码,提前致谢。

As stated in the comments, this would be more efficiently achieved if the text file was encoded in JSON.如评论中所述,如果文本文件以 JSON 编码,则会更有效地实现。 However without knowing how the text file is being produced I can't recommend a method to generate it as JSON, so here's how you might parse your current file.但是,在不知道文本文件是如何生成的情况下,我无法推荐一种将其生成为 JSON 的方法,因此这里是您解析当前文件的方法。

Assuming you're are reading the content of the text file in the frontend, you would asynchronously get the content of the text file using XMLHttpRequest .假设您正在前端读取文本文件的内容,您将使用XMLHttpRequest异步获取文本文件的内容。 Once you've received the file content you would turn it into an array.收到文件内容后,您会将其转换为数组。 In the specific case that you've provided where the text file is of the form [Skin1],[skin2],[skin3] , you would remove the first [ and last ] , and then split by the delineation ],[ .在您提供的文本文件格式为[Skin1],[skin2],[skin3]的特定情况下,您将删除第一个[和最后一个] ,然后按描述],[分割。

function httpGet(url, callback) {
    // this function gets the contents of the URL. Once the
    // content is present it runs the callback function.
    var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            callback(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", url, false );
    xmlhttp.send();    
}

httpGet("url-of-your-file", function(textFile){
    // this calls the httpGet function with the URL of your text
    // file. It then runs a function that turns the file into an
    // array.
    var array = textFile.slice(1, -1).split("],[");
    console.log(array);
});

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

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