javascript - 在 Mac OS 上通过 javascript 读取文本文件
问题描述
我想通过 javascript 读取本地文本文件。我从如何读取本地文本文件中复制了代码?
但它不工作。
这是代码片段,
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"
解决方案
推荐阅读
- ruby-on-rails - 在 Rails 控制器中循环 Ajax 数据
- typescript - 打字稿:为类减速器功能键入组合器
- python - 有没有办法同时运行两个循环(for循环,while循环,....)?
- swift - 为什么我的格子链接集成没有打开链接 UI
- javascript - 在禁用的选择元素上启用客户端验证
- linux - 如何从瞻博网络交换机获取日志消息以由 ELK 堆栈使用 filebeat 处理?
- python - 为什么这个 Python 函数不是通过引用传递的?
- python - 如何使用 OpenImages 数据集在 Keras 中训练二进制模型
- python - 混淆使用 __next__ 和 __iter__ 单独的一个代码
- php - 如何检查文件是否上传PHP