How to write data to textfile using JavaScript

落花浮王杯 提交于 2019-12-12 03:36:56

问题


I have some problem to write date to a file Test.txt by using JavaScript. I have find answer in good too but I am still can't solve it. This is my code

<script type="text/javascript">
function WriteFile()
{
   var fso  = new ActiveXObject("Scripting.FileSystemObject");
   var fh = fso.CreateTextFile("Test.txt", 8,true);
   x=document.getElementById("name").value;
   fh.WriteLine(x);
   fh.Close();
}

And

<form>
    <input type="text" id="name"/>
    <input type="button" value="Save" id="write" onclick="WriteFile()"/>
</form>

I think it's should be run well by I the simple example I see from ebook.

I am not sure with path of Test.txt. I put it in the same forder in my localhost.

What am I doing wrong?


回答1:


This the example you could go through:-

function WriteToFile(passForm) {
 
    set fso = CreateObject("Scripting.FileSystemObject"); 
    set s   = fso.CreateTextFile("<your Path>/filename.txt", True);
 
    var firstName = document.getElementById('FirstName');
    var lastName  = document.getElementById('lastName');
 
    s.writeline("First Name :" + FirstName);
    s.writeline("Last Name :" + lastName);
 
    s.writeline("-----------------------------");
    s.Close();
 }
<form onSubmit="WriteToFile(this)">
<label>Type your first name:</label>
<input type="text" name="FirstName" id="firstName" size="20">
 
<label>Type your last name: </abel>
<input type="text" name="LastName" id="lastName" size="20">
 
<input type="submit" value="submit">
</form>



回答2:


According to http://msdn.microsoft.com/en-us/library/czxefwt8(v=vs.84).aspx it looks like you need to specify the full path for your file.

E.g. "C:\\Test.txt"

Update:

Just tested this in IE9 and it works.

<head>
  <script>
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.CreateTextFile("c:\\Test.txt", 8, true);
    fh.WriteLine("foo");
    fh.Close();
  </script>
</head>


来源:https://stackoverflow.com/questions/15262356/how-to-write-data-to-textfile-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!