获取远程CSV文件并将其放入变量中

时间:2015-05-12 13:20:19

标签: javascript

我有一个简单的javascript脚本,我想在其中使用远程网址(例如https://not-my-domain.com/test.csv)中的CSV文件。

我不需要解析CSV,只是为了将其作为一个简单的字符串。我试过了:

    function getCSV() {
        var file = "https://not-my-domain.com/test.csv";
        var rawFile = new XMLHttpRequest();
        var allText;

        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function () {
            if(rawFile.readyState === 4)
                if(rawFile.status === 200 || rawFile.status == 0)
                    allText = rawFile.responseText;
        };

        rawFile.send();
        alert(allText); //UNDEFINED!
        return allText;
   }

但是在函数终止后,allText仍然是undefined。如果你能帮我解决这个小问题,我很高兴。

1 个答案:

答案 0 :(得分:1)

使用lambda进行简单的回调。您需要一个代理来获取远程域csv,或者确保它已启用了cors。

function getCSV(func) {
        var file = "https://not-my-domain.com/test.csv";
        var rawFile = new XMLHttpRequest();
        var allText;

        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function () {
            if(rawFile.readyState === 4)
                if(rawFile.status === 200 || rawFile.status == 0)
                    allText = rawFile.responseText;
                    if(func!=undefined && typeof(func) == "function"){
                        func(allText);
                     }
        };

        rawFile.send();


}


getCSV(function(contents){
  alert(contents);
})