簡體   English   中英

如何使用Javascript將表單輸入數據保存到XML文件?

[英]How to save form input data to a XML file using Javascript?

我想將這些表單輸入保存在文件(例如XML)中,以便以后可以在表單中再次使用它:

<html>
    <body>
        <form action="demo_form.asp">
            First name: <input type="text" name="FirstName" value="Mickey"><br>
            Last name: <input type="text" name="LastName" value="Mouse"><br>
            <input type="submit" value="Submit">
        </form>

        <p>Click the "Submit" button and the form-data will be sent to a page on the server called "demo_form.asp".</p>

    </body>
</html>

實現這一目標的最簡單方法是什么? 我不能使用PHP或ASP.NET。

除非您使用服務器端語言將數據保存到文件系統(我假設您的意思是希望保存XML文件)是不可能的。 JavaScript應用程序無法寫入文件系統。

您可以使用HTML5的存儲功能 並查看“ 如何使用HTML5存儲從表單中保存數據

您要問的只能在服務器端完成!

根據您的問題,我可以理解您是Web開發的新手,我知道您只想保留數據,以便以后可以按需使用

我的建議是將cookie或url或hidden字段中的值保存為XML字符串,最好選擇隱藏字段。

如果您需要將數據保存到服務器,那么您將需要服務器端工具ASP.NET或PHP,如您所說。

但是,您說您希望以XML格式存儲數據,以便以后可以在表單中使用它 您可以稍后在同一頁面中使用這些數據並將其放入XML中,如下所示:

interval=setInterval(function(){
    first=$('[name*="FirstName"]').val();
    last=$('[name*="LastName"]').val();
    output='<data><first>'+first+'</first><last>'+last+'</last></data>';
    $('#output').text(output);
},200);

http://jsfiddle.net/pA8nC/

但我想不出你為什么要這樣做的任何理由! 您可以使用純JavaScript或JQuery直接訪問值:

JQuery的:

firstName=$('[name*="FirstName"]').val();
lastName=$('[name*="LastName"]').val();

JS:

firstName=document.form.FirstName.value;
lastName=document.form.LastName.value;

下面的代碼示例將允許您從頁面上的字段中獲取數據,並將它們直接寫入txt文件到用戶本地框。 我目前正在尋找一種方法將它們寫入XMl以用於我所在的項目,但至少我可以將我想要寫入的數據寫入文本文件。

var userInput = document.getElementById("userInputId").value;

var fileURL = 'data:application/notepad;charset=utf-8,' + encodeURIComponent(userInput);
var fileName = "test.txt";


if (!window.ActiveXObject) {
  var save = document.createElement('a');
  save.href = fileURL;

  save.target = '_blank';
  save.download = fileName || 'unknown';

  var event = document.createEvent('Event');
  event.initEvent('click', true, true);
  save.dispatchEvent(event);
  (window.URL || window.webkitURL).revokeObjectURL(save.href);
}

// for IE
else if (!!window.ActiveXObject && document.execCommand) {
  var _window = window.open(fileURL, '_blank');
  _window.document.close();
  _window.document.execCommand('SaveAs', true, fileName || fileURL)
  _window.close();
}

在提交表單時,此javascript將觸發表單數據(對於每個表單)的文件下載。 它不使用XML,因為我不知道你的模式是什么樣的(我質疑它是有用的,而表單序列化的字符串可以使用xhr快速發布)。

http://jsfiddle.net/CKvcV/

(function () {
   var makeTextFile = function (text) {
        var data = new Blob([text], {type: 'text/plain'});
        return window.URL.createObjectURL(data);
      },
      serializeForm = function(form, evt){
        var evt    = evt || window.event;
        evt.target = evt.target || evt.srcElement || null;
        var field, query='';
        if(typeof form == 'object' && form.nodeName == "FORM"){
            for(i=form.elements.length-1; i>=0; i--){
                field = form.elements[i];
                if(field.name && field.type != 'file' && field.type != 'reset'){
                    if(field.type == 'select-multiple'){
                        for(j=form.elements[i].options.length-1; j>=0; j--){
                            if(field.options[j].selected){
                                query += '&' + field.name + "=" + encodeURIComponent(field.options[j].value).replace(/%20/g,'+');
                            }
                        }
                    }
                    else{
                        if((field.type != 'submit' && field.type != 'button') || evt.target == field){
                            if((field.type != 'checkbox' && field.type != 'radio') || field.checked){
                                query += '&' + field.name + "=" + encodeURIComponent(field.value).replace(/%20/g,'+');
                            }   
                        }
                    }
                }
            }
        }
        return query.substr(1);
    }
   , _onsubmit = function() {
        var _href = makeTextFile(serializeForm(this));
        var _a = document.createElement("A");
        _a.setAttribute('download', 'export.txt');
        _a.setAttribute('target', '_blank');
        _a.href = _href;
        _a.click();
        window.URL.revokeObjectURL(_href);
        //return false;
    };

    [].forEach.call(
        document.querySelectorAll('form'),
        function(f) { f.onsubmit = _onsubmit; }
        );
})();

將其構建為書簽或其他任何內容。 但是如果你想節省一些打字,你可能希望將值存儲在localStorage而不是文件中。 您沒有提到如何重用數據,從localStorage中提取數據要比構建動態文件上傳器並讓用戶找到正確的文件要容易得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM