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

时间:2013-04-17 08:39:05

标签: javascript jquery html file-io 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>

这样可以正常工作,并且能够将我的新数据附加到文件中。

但我想根据我传递的ID更新特定的行内容 我搜索了很多,但找不到任何。

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

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

1 个答案:

答案 0 :(得分:10)

我们的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>

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);
}

检查特定行:

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!"); }
    }
}

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

相关问题