简体   繁体   中英

How to add data to file in javascript?

I want to make registration form and write the data into data.txt using ActiveXObject. What I write is

<script type="text/javascript">
    function WriteFile()
    {
       var fso  = new ActiveXObject("Scripting.FileSystemObject");
       var fh = fso.CreateTextFile("E:\\Test.txt", true);
       x=document.getElementById("name").value;
       y=document.getElementById("password").value;
       fh.WriteLine(x+"#"+y);
       fh.Close();
    }
</script>
<BODY>
<form>
    <input type="text" id="name"/>
    <input type="text" id="password"/>
    <input type="button" value="Sign Up" id="write" onclick="WriteFile()"/>
</form>
</BODY>

When I tried that way, every time I click Sign Up button, the new data override the previous data. I tried to use fh.AppendLine(x + "#" + y) but it didn't work.

Could anyone help me how to add data, not override data?

I've done stuff like this a long time ago... (when I was using windows) I think it is because you're replacing the file with a new file with CreateTextFile so if the file already exists you'll need to do this:

function AppendLine()
{
   var fso  = new ActiveXObject("Scripting.FileSystemObject");
   var fh = fso.OpenTextFile("E:\\Training Asslab\\Advance\\Write to File\\Test.txt", 8, True);
   x=document.getElementById("name").value;
   y=document.getElementById("password").value;
   fh.WriteLine(x+"#"+y);
   fh.Close();
}

CreateTextFile overrwrites the current file, I think. You should use FileExists to check its presence before creating it. If it does exist you can use OpenTextFile.

Here's the relevant documentation

Disclaimer You should never use those functions. They only work in IE and are horrible.

I think your problem stems from using CreateTextFile . You should instead be using OpenTextFile with the second parameter set to 8 . That will allow for appending.

Use OpenTextFile method with create flag and ForAppending mode instead of CreateTextFile .

However, do understand, that you're not only limiting yourself to very old IE version and inside trusted zone, but you're also leaving files on user's local drives, not on your server. Because of that you can't do anything with this "registration data".

use ("E:\\\\Test.txt", 8); . 8 is a mode to append. and thus, i'm wondering whether you're having the same homework as me or not, since i'm having the same problem too, but i'm stuck in the AvtiveXObject line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM