jQuery 如何将数据从文本文件加载到 javascript 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17901622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:10:50  来源:igfitidea点击:

how to load data from text file to javascript array?

javascriptjquery

提问by user1788736

i have an array called items=["apple","mango","cherry"];

我有一个名为的数组 items=["apple","mango","cherry"];

i wonder how i can load the array data from text file instead of declaring it?the text file data is stored like this "apple","mango","cherry",...

我想知道如何从文本文件加载数组数据而不是声明它?文本文件数据的存储方式类似于“apple”、“mango”、“cherry”、...

furthermore, how to add to the end of this this text file an item for example add "orange" after "cherry"?

此外,如何在此文本文件的末尾添加一个项目,例如在“樱桃”之后添加“橙色”?

items=["apple","mango","cherry"];
    if (items.indexOf(myVariable2) == -1) {

     // not found, so output it
       t++;

    document.myform3.outputtext3.value +=myVariable2+"\n";

    }

回答by iConnor

With jQuery you can do something like this

使用 jQuery 你可以做这样的事情

  $.get("textFile.txt", function(data) {
      var items = data.split(',');
  });

You may need something like this though

你可能需要这样的东西

var items = data.replace(/"/g, '').split(',');

This is a start.

这是一个开始。

If this is a user input file then you may need to upload it before you work with it.

如果这是一个用户输入文件,那么您可能需要在使用它之前上传它。

回答by Shiva

Sorry, but I don't believe it's quite that simple. Browsers restrict access to local drives (and to server drives) for security reasons.

抱歉,但我不相信事情这么简单。出于安全原因,浏览器会限制对本地驱动器(和服务器驱动器)的访问。

But one way to access the text file using jQuery would be

但是使用 jQuery 访问文本文件的一种方法是

jQuery.get('http://localhost/foo.txt', function(data) {
    var myvar = data;
});

回答by user1788736

 var file = event.target.file;
 var reader = new FileReader();
 var txt=reader.readAsText(file);
 var items=txt.split(",");