This question already has answers here:
How do I return the response from an asynchronous call?
                                
                                    (38个答案)
                                
                        
                                2年前关闭。
            
                    
我正在尝试使用一个函数读取csv文件并返回它。但不幸的是我有一个空字符串

function getStations() {

    var final_results = [];

    $.ajax({
        type: "GET",
        url: "CSV.csv",
        dataType: "text",
        success: function (data) {
            var lines = data.split(/\r\n|\n/);

            //Set up the data arrays
            var stations_data = [];

            //var headings = lines[0].split(','); // Splice up the first row to get the headings
            for (var j = 1; j < lines.length; j++) {
                var values = lines[j].split(','); // Split up the comma seperated values
                // We read the key,1st, 2nd and 3rd rows

                // tmp_data.push(parseFloat(values[0]));
                //tmp_data.push(parseFloat(values[1]));
                //tmp_data.push(parseFloat(values[2]));
                //tmp_data.push(values[4]);
                stations_data.push(values[4]);
                final_results.push(values[4]);
            }

            console.log("inside:" + final_results.length)
        }
    });

    // Let's process the data from the data file
    console.log("outside: " + final_results.length);
}


结果如下:
console.log results

有什么建议?

最佳答案

console.log('outside..语句在ajax完成之前被执行。
final_results加载时,您将必须执行某种回调。

function getStations(callback) {

    var final_results = [];

    $.ajax({
        type: "GET",
        url: "CSV.csv",
        dataType: "text",
        success: function (data) {
            var lines = data.split(/\r\n|\n/);

            //Set up the data arrays
            var stations_data = [];

            //var headings = lines[0].split(','); // Splice up the first row to get the headings
            for (var j = 1; j < lines.length; j++) {
                var values = lines[j].split(','); // Split up the comma seperated values
                // We read the key,1st, 2nd and 3rd rows

                // tmp_data.push(parseFloat(values[0]));
                //tmp_data.push(parseFloat(values[1]));
                //tmp_data.push(parseFloat(values[2]));
                //tmp_data.push(values[4]);
                stations_data.push(values[4]);
                final_results.push(values[4]);
            }

            callback(final_results)
        }
    });
}

getStations(function (final_results){
    console.log("outside: " + final_results.length);
})

07-24 09:24