我有一個簡單的javascript腳本,我想使用存在於遠程URL(例如https://not-my-domain.com/test.csv
)中的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
函數終止後。如果你能幫助我解決這個小問題,我會很高興。
您正試圖在文件加載完成前提醒內容。 – Andy
好吧,我懷疑是這樣。如何在加載完成之前阻止程序? – matan129
考慮在'onreadystatechange'內部放置'alert'(或者做其他必要的處理),否則它會在Ajax請求完成之前觸發。 –