无法弄清楚 $.get 上的回调以将文本文件读取到数组中

Can't figure out callback on $.get to read text file into an array

本文关键字:文件 文本 读取 数组 回调 弄清楚 get      更新时间:2023-09-26

我只想从这个文本文件中获取数据,稍微解析一下,然后将其扔到几个数组中。aJax 的异步性质(我甚至不知道我在使用...?(意味着在我尝试访问它之前,数组仍在填充中。这似乎给我造成了一种完全无用的情况,因为我需要在用户访问站点期间的不同时间访问数组。有什么想法吗?

var words = new Array();
var sylls = new Array();
var csv_file = new Array(); // for word arrays
$(document).ready(function(){
    readWords( addWords );
});
function readWords( process ) {
        $.get('terms.csv', function(data){
                csv_file = data.split(''n');
                    // csv file is now in an array, split into seperate word array and syllable array
                    for (var i = 0; i < csv_file.length; i++) {
                        var both = csv_file[i].split(',');  // split at the comma
                        words[i] = both[0]; // populate word array
                        sylls[i] = both[1]; // populate syllable array
                        //put_word(words[i], sylls[i]);
                    };
            });   
    process(words, sylls);
}
function addWords(w, ss){
    console.log(w);
}

这一切最终都会返回一个空数组。

编辑--解决方案:

不确定为什么以前没有人建议这样做,但对于那些像我一样对 ajax 感到沮丧的人来说,这是一个简单的解决方案!

var words = new Array();
var sylls = new Array();
var csv_file = new Array(); // for word arrays
$(document).ready(function(){
    get_words();
});
function get_words() {

        $.get('terms.csv', function(data){
            //async: false;
            csv_file = data.split(''n');
                // csv file is now in an array, split into seperate word array and syllable array
                for (var i = 0; i < csv_file.length; i++) {
                    var both = csv_file[i].split(',');  // split at the comma
                    words[i] = both[0]; // populate word array
                    sylls[i] = both[1]; // populate syllable array
                    //put_word(words[i], sylls[i]);
                };
            })
        .done(function() {
            // once it's done DO THIS STUFF
        });
}
看起来

process(words, sylls);$.get()块之外。 .$.get()是一个异步(默认情况下(请求,因此当您的程序调用它时,它会立即返回并执行process(),而无需必要的数据。只需在$.get()块结束之前添加process()调用即可。