在Mac OS上通过JavaScript读取文本文件

时间:2018-07-12 07:35:52

标签: javascript file xmlhttprequest httprequest onreadystatechange

我想通过javascript读取本地文本文件。我从How to read a local text file?

复制了代码

,但不起作用。

这是代码段,

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);

    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    console.log(rawFile);
     rawFile.send(null);
}

readTextFile("file:///Users/vivek/Desktop/file1.txt");

我尝试打印对象(rawFile),这是我得到的输出,

[object XMLHttpRequest] {
  abort: function abort() { [native code] },
  addEventListener: function addEventListener() { [native code] },
  dispatchEvent: function dispatchEvent() { [native code] },
  DONE: 4,
  getAllResponseHeaders: function getAllResponseHeaders() { [native code] },
  getResponseHeader: function getResponseHeader() { [native code] },
  HEADERS_RECEIVED: 2,
  LOADING: 3,
  onabort: null,
  onerror: null,
  onload: null,
  onloadend: null,
  onloadstart: null,
  onprogress: null,
  onreadystatechange: function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    },
  ontimeout: null,
  open: function open() { [native code] },
  OPENED: 1,
  overrideMimeType: function overrideMimeType() { [native code] },
  readyState: 1,
  removeEventListener: function removeEventListener() { [native code] },
  response: "",
  responseText: "",
  responseType: "",
  responseURL: "",
  responseXML: null,
  send: function send() { [native code] },
  setRequestHeader: function setRequestHeader() { [native code] },
  status: 0,
  statusText: "",
  timeout: 0,
  UNSENT: 0,
  upload: [object XMLHttpRequestUpload] {
    addEventListener: function addEventListener() { [native code] },
    dispatchEvent: function dispatchEvent() { [native code] },
    onabort: null,
    onerror: null,
    onload: null,
    onloadend: null,
    onloadstart: null,
    onprogress: null,
    ontimeout: null,
    removeEventListener: function removeEventListener() { [native code] }
  },
  withCredentials: false
}

readyState的值为1,因此我尝试将条件if(rawFile.readyState === 4)更改为if(rawFile.readyState === 1),但还是没有运气。

这是错误,我正在使用JSBin,

"error"
"Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///Users/vivek/Desktop/file1.txt'.
    at readTextFile (gazoqoq.js:18:14)
    at gazoqoq.js:21:1
    at https://static.jsbin.com/js/prod/runner-4.1.4.min.js:1:13924
    at https://static.jsbin.com/js/prod/runner-4.1.4.min.js:1:10866"

0 个答案:

没有答案