将 .txt 文件读入数组 Javascript/jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14969741/
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
Reading .txt file into array Javascript/jQuery
提问by spogebob92
I am trying to read a file (stored on the web server) into an array. When I print the array I currently get "undefined". Here is the code im using:
我正在尝试将文件(存储在 Web 服务器上)读入数组。当我打印数组时,我当前得到“未定义”。这是我使用的代码:
var cardRules = new Array;
$.get('UserFile.txt', function(data){
var array = data.split('\n');
console.log(cardRules);
});
Any help would be appreciated!
任何帮助,将不胜感激!
回答by Chris Hughes
The 'cardRules' variable never gets populated with the array data. Instead of
var array = data.split('\n');
just use
cardRules = data.split('\n');
'cardRules' 变量永远不会被数组数据填充。而不是
var array = data.split('\n');
仅仅使用
cardRules = data.split('\n');
回答by Motsim
Try full url instead of just relative linking
尝试完整的 url 而不是相对链接
http://yoursite.com/yourfilelocation/yourfile.txt
http://yoursite.com/yourfilelocation/yourfile.txt
$.get('http://yoursite.com/yourfilelocation/yourfile.txt', function(data){
var cardRules = data.split('\n');
console.log(cardRules);
});
$.get('http://yoursite.com/yourfilelocation/yourfile.txt', function(data){
var cardRules = data.split('\n');
console.log(cardRules);
});
回答by kraYz
var cardRules = new Array();
$.get('UserFile.txt', function(data){
cardRules = data.split('\n');
console.log(cardRules);
});