无法找出$ .get上的回调来将文本文件读入数组

时间:2013-10-02 21:27:11

标签: javascript

我只想从这个文本文件中获取数据,稍微解析一下,然后把它扔进几个数组中。 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);
}

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

编辑 - SOLUTION:

我不确定为什么之前没有人提出这个问题,但是对于那些像我一样对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
        });

}

1 个答案:

答案 0 :(得分:1)

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