如何使用 JavaScript 将数据写入文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15262356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write data to textfile using JavaScript
提问by sk juli kaka
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
我在使用 JavaScript 将日期写入文件 Test.txt 时遇到了一些问题。我也找到了很好的答案,但我仍然无法解决。这是我的代码
<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.
我不确定 Test.txt 的路径。我把它放在我的本地主机的同一个文件夹中。
What am I doing wrong?
我究竟做错了什么?
回答by MADHUR GUPTA
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>
回答by doesterr
According to http://msdn.microsoft.com/en-us/library/czxefwt8(v=vs.84).aspxit looks like you need to specify the full path for your file.
根据http://msdn.microsoft.com/en-us/library/czxefwt8(v=vs.84).aspx,您似乎需要为文件指定完整路径。
E.g. "C:\\Test.txt"
例如 "C:\\Test.txt"
Update:
更新:
Just tested this in IE9 and it works.
刚刚在 IE9 中测试了这个,它可以工作。
<head>
<script>
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.CreateTextFile("c:\Test.txt", 8, true);
fh.WriteLine("foo");
fh.Close();
</script>
</head>