javascript - 在 JavaScript 中读/写文件

标签 javascript file file-io fopen fread

我正在尝试制作一个网络应用程序,它将读取服务器端 CSV 文件并以简洁、可浏览的格式显示它。问题是我想用裸 JS/CSS3/HTML5 来做。 有没有办法用裸露的 JS/CSS3/HTML5 读写服务器端文件?我显然希望它独立于操作系统/浏览器。

我尝试过的

<小时/>

已经尝试实现一些我在网上找到的代码(一些网站引用了它)。以下是我在测试时尝试的内容:(我只想测试在网页中显示网页本身的内容)

scriptTest.htm :

<html>
<head>
<script type="text/javascript" src="readIt.JS"></script>
</head>
<body>
<button onclick="return readIt();">Show the code of the page</button>
<div id="readItOutput"></div>
</body>
</html>

readIt.JS :

function readIt()
{
    file = fopen(getScriptPath("scriptTest.htm"), 0);
    file_length = flength(file);
    content = fread(file, file_length);
    document.getElementById("readIt").innerText = content;
}

但是,每当我在 Opera 和 Chrome 下运行它时,它都会抛出以下错误:

歌剧:

Uncaught exception: ReferenceError: Undefined variable: fopen
Error thrown at line 3, column 1 in readIt() in http://s.supuhstar.operaunite.com/s/content/JS/readIt.JS:
    file = fopen(getScriptPath("scriptTest.htm"), 0);
called from line 1, column 0 in <anonymous function>(event) in http://s.supuhstar.operaunite.com/s/content/JS/scripttest.htm:
    return readIt();

Chrome:

Uncaught ReferenceError: getScriptPath is not defined
readItreadIt.JS:3
(anonymous function)scripttest.htm:6
onclick

最佳答案

如果你想从服务器编辑一些文件,你需要使用 XHR 对象将文件下载到客户端,然后再次使用 XHR 对象将修改后的数据发送回服务器,你还需要服务器上的某种 API 来发送/接收数据。

关于javascript - 在 JavaScript 中读/写文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9187860/

相关文章:

javascript - 尝试在服务文件中使用 ng-model

javascript - 在react+react-router-dom中将函数引用传递给sibling-ish

mysql - 从脚本运行 mysql -vvv,我没有记录

java - 如何将数据从文本文件导入到 JTextArea?

javascript - LokiJS 不允许插入 Json 数据

javascript - 表单中不发送按钮数据

c - 包含字符串和整数的打印文件,C 程序

C 在字符串中搜索单词

perl - 集群:用sysopen截断的正确方法

c++ - 如何在C++中写入文件而不锁定它?