简体   繁体   English

如何用JavaScript写入txt文件

[英]How to write in txt file with JavaScript

I want to save something in txt file by using JavaScipt 我想使用JavaScipt在txt文件中保存一些东西

<input type="date" id="date1">
  <script>
  var a=document.getElementByid("date1");
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.CreateTextFile("Test.txt", 8, true);
    fh.WriteLine("Something");
    fh.Close();

  </script>

I tried this but it's not working. 我尝试了这个,但它不起作用。 My main idea is to get value form input and save it in Test.txt 我的主要想法是获取值表单输入并将其保存在Test.txt

You can't; 你不能; not reliably, cross-browser. 不可靠,跨浏览器。 JavaScript in the browser (where you're clearly using it) runs in a sandbox and is not allowed to access the local filesystem. 浏览器中的JavaScript(您明显使用它)在沙箱中运行,不允许访问本地文件系统。 Some older versions of IE will allow you to use the FileSystemObject in the way shown in your question, but only with masses of security warnings, and modern versions don't allow it at all. 一些旧版本的IE将允许您以问题中显示的方式使用FileSystemObject ,但只有大量安全警告,而现代版本根本不允许使用它。

The File API and FileSystem API allow limited reading from files in the file system, but writing is still a work in progress. File APIFileSystem API允许从文件系统中的文件进行有限读取 ,但写入仍在进行中。

Your best bet is to post a form to your server, probably with target="_blank" , and have the server respond with a Content-Disposition: attachment; filename=Test.txt 您最好的选择是将表单发布到您的服务器,可能使用target="_blank" ,并让服务器使用Content-Disposition: attachment; filename=Test.txt Content-Disposition: attachment; filename=Test.txt header and the file data, which will cause the browser to ask the user where to save it. Content-Disposition: attachment; filename=Test.txt标头和文件数据,这将导致浏览器询问用户保存位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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