使用javascript将数据写入本地文本文件

Mad*_*llu 8 html javascript file-io jquery hta

我已经创建了一个过程来将内容写入本地计算机中的文本文件.

<form id="addnew">
    <input type="text" class="id">
    <input type="text" class="content">
    <input type="submit" value="Add">
</form>
<script>
    jQuery(function($) {
        $('#form_addjts').submit(function(){
            writeToFile({
                id: $(this).find('.id').val(), 
                content: $(this).find('.content').val()
            });
            return false;
        }); 
        function writeToFile(data){
            var fso = new ActiveXObject("Scripting.FileSystemObject");
            var fh = fso.OpenTextFile("D:\\data.txt", 8);
            fh.WriteLine(data.id + ',' + data.content);
            fh.Close(); 
        } 
    }); 
</script>
Run Code Online (Sandbox Code Playgroud)

这工作正常,能够将我的新数据附加到文件中.

但我想根据我传递的ID更新特定的行CONTENT.
我搜索了很多,但找不到任何东西.

如何根据ID更新文件中的特定行?

注意: - 我没有使用任何服务器.我有一个html文件(包含所有功能),我将在本地计算机上运行.

aki*_*uri 9

我们的HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>
Run Code Online (Sandbox Code Playgroud)

JS(写入txt文件):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}
Run Code Online (Sandbox Code Playgroud)

检查特定行:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}
Run Code Online (Sandbox Code Playgroud)

将这些放在.hta文件中并运行它.测试W7,IE11.它正在发挥作用.如果你想让我解释一下发生了什么,请这样说.

  • @Everyone_Else 这并不奇怪。OP 正在使用可在 IE 中运行的 ActiveX。此外,其他浏览器不允许访问本地文件。 (2认同)
  • 这是一个糟糕的答案。好的答案对于提出相同问题且不使用 IE 的其他人很有用。 (2认同)