【问题标题】:Can I save input from form to .txt in HTML, using JAVASCRIPT/jQuery, and then use it?我可以使用 JAVASCRIPT/jQuery 将输入从表单保存到 HTML 中的 .txt,然后使用它吗?
【发布时间】:2012-12-03 14:26:08
【问题描述】:

是否可以将文本输入(本地)从表单保存到文本文件,然后打开该文档以供以后使用?

只使用 HTML、javascript 和 jQuery。没有数据库或 php。

/W

【问题讨论】:

  • 方法错误。即使可能,这也不是网页的目的。
  • 这个问题的答案取决于你是指服务器端还是客户端

标签: javascript jquery html css xhtml


【解决方案1】:

只有当用户允许它像下载一样保存并且他必须手动打开它时才能保存,唯一的问题是建议一个名称,我的示例代码将只为 Google Chome 建议一个名称,并且仅当由于download 属性,您使用链接而不是按钮。

您只需要 base64 encode library 和 JQuery 即可轻松完成。

// This will generate the text file content based on the form data
function buildData(){
  var txtData = "Name: "+$("#nameField").val()+
      "\r\nLast Name: "+$("#lastNameField").val()+
      "\r\nGender: "+($("#genderMale").is(":checked")?"Male":"Female");

  return txtData;
}
// This will be executed when the document is ready
$(function(){
  // This will act when the submit BUTTON is clicked
  $("#formToSave").submit(function(event){
    event.preventDefault();
    var txtData = buildData();
    window.location.href="data:application/octet-stream;base64,"+Base64.encode(txtData);
  });

  // This will act when the submit LINK is clicked
  $("#submitLink").click(function(event){
    var txtData = buildData();
    $(this).attr('download','sugguestedName.txt')
      .attr('href',"data:application/octet-stream;base64,"+Base64.encode(txtData));
  });
});
<!DOCTYPE html>
<html>
    <head><title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="base64.js"></script>
    </head>
    <body>
    <form method="post" action="" id="formToSave">
        <dl>
            <dt>Name:</dt>
            <dd><input type="text" id="nameField" value="Sample" /></dd>
            <dt>Last Name:</dt>
            <dd><input type="text" id="lastNameField" value="Last Name" /></dd>
            <dt>Gender:</dt>
            <dd><input type="radio" checked="checked" name="gender" value="M" id="genderMale" />
                Male
                <input type="radio" checked="checked" name="gender" value="F" />
                Female
        </dl>
        <p><a href="javascript://Save as TXT" id="submitLink">Save as TXT</a></p>
        <p><button type="submit"><img src="http://www.suttonrunners.org/images/save_icon.gif" alt=""/> Save as TXT</button></p>
    </form>
    </body>
</html>

【讨论】:

    【解决方案2】:

    如果你问我最好的解决方案是这个。 这将使用您选择的文件名保存文件,并使用按钮自动保存为 HTML 或 TXT。

    示例:

    function download(filename, text) {
      var pom = document.createElement('a');
      pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 
    
    encodeURIComponent(text));
      pom.setAttribute('download', filename);
    
      pom.style.display = 'none';
      document.body.appendChild(pom);
    
      pom.click();
    
      document.body.removeChild(pom);
    }
    
    function addTextHTML()
    {
        document.addtext.name.value = document.addtext.name.value + ".html"
    }
    
    function addTextTXT()
    {
        document.addtext.name.value = document.addtext.name.value + ".txt"
    }
    <html>
      <head></head>
      <body>
    
        <form name="addtext" onsubmit="download(this['name'].value, this['text'].value)">
    
        <textarea rows="10" cols="70" name="text" placeholder="Type your text here:"></textarea>
        <br>
        <input type="text" name="name" value="" placeholder="File Name">
        <input type="submit" onClick="addTextHTML();" value="Save As HTML">
        <input type="submit" onClick="addTexttxt();" value="Save As TXT">
    
        </form>
      </body>
    </html>

    【讨论】:

      【解决方案3】:

      据我了解,您必须将用户的输入本地保存到文本文件中。

      检查此链接。看看这是否有帮助。

      Saving user input to a text file locally

      【讨论】:

        【解决方案4】:

        这将用于从 HTML 页面加载文件并将文件保存到 TXT 中并选择另存为

        <html>
        <body>
        
        <table>
            <tr><td>Text to Save:</td></tr>
            <tr>
                <td colspan="3">
                    <textarea id="inputTextToSave" cols="80" rows="25"></textarea>
                </td>
            </tr>
            <tr>
                <td>Filename to Save As:</td>
                <td><input id="inputFileNameToSaveAs"></input></td>
                <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
            </tr>
            <tr>
                <td>Select a File to Load:</td>
                <td><input type="file" id="fileToLoad"></td>
                <td><button onclick="loadFileAsText()">Load Selected File</button><td>
            </tr>
        </table>
        
        <script type="text/javascript">
        
        function saveTextAsFile()
        {
            var textToSave = document.getElementById("inputTextToSave").value;
            var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
            var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
            var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
        
            var downloadLink = document.createElement("a");
            downloadLink.download = fileNameToSaveAs;
            downloadLink.innerHTML = "Download File";
            downloadLink.href = textToSaveAsURL;
            downloadLink.onclick = destroyClickedElement;
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
        
            downloadLink.click();
        }
        
        function destroyClickedElement(event)
        {
            document.body.removeChild(event.target);
        }
        
        function loadFileAsText()
        {
            var fileToLoad = document.getElementById("fileToLoad").files[0];
        
            var fileReader = new FileReader();
            fileReader.onload = function(fileLoadedEvent) 
            {
                var textFromFileLoaded = fileLoadedEvent.target.result;
                document.getElementById("inputTextToSave").value = textFromFileLoaded;
            };
            fileReader.readAsText(fileToLoad, "UTF-8");
        }
        
        </script>
        
        </body>
        </html>
        

        【讨论】:

          【解决方案5】:

          您可以使用localStorage 保存数据以备后用,但您不能使用JavaScript(在浏览器中)将数据保存到文件

          要全面: 您不能在浏览器中使用 JavaScript 将内容存储到文件中,但是using HTML5,您可以读取文件。

          【讨论】:

            【解决方案6】:

            或者这也会以相同的方式工作,但没有保存选项:

            <!DOCTYPE html>
            <html>
            <head>
            
            
            <script type='text/javascript'>//<![CDATA[
            window.onload=function(){
            (function () {
            var textFile = null,
              makeTextFile = function (text) {
                var data = new Blob([text], {type: 'text/plain'});
            
                // If we are replacing a previously generated file we need to
                // manually revoke the object URL to avoid memory leaks.
                if (textFile !== null) {
                  window.URL.revokeObjectURL(textFile);
                }
            
                textFile = window.URL.createObjectURL(data);
            
                return textFile;
              };
            
            
              var create = document.getElementById('create'),
                textbox = document.getElementById('textbox');
            
              create.addEventListener('click', function () {
                var link = document.getElementById('downloadlink');
                link.href = makeTextFile(textbox.value);
                link.style.display = 'block';
              }, false);
            })();
            
            }//]]> 
            
            </script>
            
            
            </head>
            
            <body>
              <textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>
            
            
              <script>
              // tell the embed parent frame the height of the content
              if (window.parent && window.parent.parent){
                window.parent.parent.postMessage(["resultsFrame", {
                  height: document.body.getBoundingClientRect().height,
                  slug: "qm5AG"
                }], "*")
              }
            </script>
            
            </body>
            
            </html>
            

            【讨论】:

              【解决方案7】:

              如果不使用服务器端逻辑,您无法将其保存为本地文件。但是,如果这符合您的需求,您可以查看 html5 的本地存储或我们的 javascript 插件 jStorage

              【讨论】:

                【解决方案8】:

                答案是肯定的

                <html>
                <head>
                </head>
                <body>
                <script language="javascript">
                function WriteToFile()
                {
                var fso = new ActiveXObject("Scripting.FileSystemObject");
                var s = fso.CreateTextFile("C:\\NewFile.txt", true);
                var text=document.getElementById("TextArea1").innerText;
                s.WriteLine(text);
                s.WriteLine('***********************');
                s.Close();
                }
                </script>
                
                <form name="abc">
                <textarea name="text">FIFA</textarea>
                <button onclick="WriteToFile()">Click to save</Button>  
                </form> 
                
                </body>
                </html>
                

                【讨论】:

                • ... 这仅适用于 InternetExplorer,并且仅在安全设置允许的情况下。
                • 我只看到 ActiveXObject;我认为这只是 IE?
                • 正确!请注意,允许此功能非常不安全
                猜你喜欢
                • 2018-08-06
                • 1970-01-01
                • 2022-06-10
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-01-20
                • 1970-01-01
                相关资源
                最近更新 更多