[英]I need to read a text file from a javascript
我正在編寫帶有javascript的網頁,以便根據用戶請求從服務器讀取文本格式的數據文件。 加載文本文件后,我需要稍微操縱一下數據。
我一直在使用XMLHttpRequest進行加載,但是現在我看到同步請求被“棄用”了。 我無法在加載數據之前開始操作數據,所以在這種情況下我該怎么辦?
function doGET(path, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// The request is done; did it work?
if (xhr.status == 200) {
// ***Yes, use `xhr.responseText` here***
callback(xhr.responseText);
} else {
// ***No, tell the callback the call failed***
callback(null);
}
}
};
xhr.open("GET", path);
xhr.send();
}
function handleFileData(fileData) {
if (!fileData) {
// Show error
return;
}
// Use the file data
}
// Do the request
doGET("/path/to/file", handleFileData);
或者使用promises,這是處理回調的更現代的方式(但繼續閱讀):
function doGET(path, callback) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { // The request is done; did it work? if (xhr.status == 200) { // Yes, use `xhr.responseText` to resolve the promise resolve(xhr.responseText); } else { // No, reject the promise reject(xhr); } } }; xhr.open("GET", path); xhr.send(); }); } // Do the request doGET("/path/to/file") .then(function(fileData) { // Use the file data }) .catch(function(xhr) { // The call failed, look at `xhr` for details });
在2019年,沒有理由將XHR包含在這樣的承諾中,只需使用fetch
:
function doGET(url) {
return fetch(url).then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status); // Rejects the promise
}
});
}
由於您要處理本地文件,請嘗試此操作
function readFile(file)
{
var f = new XMLHttpRequest();
f.open("GET", file, false);
f.onreadystatechange = function ()
{
if(f.readyState === 4)
{
if(f.status === 200 || f.status == 0)
{
var res= f.responseText;
alert(res);
}
}
}
f.send(null);
}
然后你必須使用File:\\\\
調用File:\\\\
readFile('File:\\\yourpath');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.