我需要从javascript中读取文本文件

OZ1*_*SEJ 5 javascript xmlhttprequest

我正在编写带有javascript的网页,以便根据用户请求从服务器读取文本格式的数据文件.加载文本文件后,我需要稍微操纵一下数据.

我一直在使用XMLHttpRequest进行加载,但是现在我看到同步请求被"弃用"了.我无法在加载数据之前开始操作数据,所以在这种情况下我该怎么办?

T.J*_*der 11

使用一个同步的请求:

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);
Run Code Online (Sandbox Code Playgroud)

或者使用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
    });
Run Code Online (Sandbox Code Playgroud)

  • 我现在明白了这一点。我只需要解决这个问题。我花了一个小时的时间来打扫浴室,然后打到我了;-)谢谢! (2认同)

San*_*kar 5

既然你想处理本地文件,试试这个

利用XMLHttpRequest

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);
}
Run Code Online (Sandbox Code Playgroud)

然后你必须打电话给File:\\

readFile('File:\\\yourpath');
Run Code Online (Sandbox Code Playgroud)

  • @OZ1SEJ:只需将处理文件数据的代码放入接受参数的函数中,并在数据准备好时让异步代码调用该函数。我已经更新了 CW 答案以表明这样做。 (2认同)