如何使用Javascript将表单输入数据保存到XML文件?

时间:2021-11-23 01:04:20

I want to save these form inputs in a file (e.g XML) in order to be able to use it later in the form again:

我想将这些表单输入保存在一个文件(例如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>

What is the easiest way to achieve this? I can't use PHP or ASP.NET.

实现这一目标的最简单方法是什么?我不能使用PHP或ASP.NET。

5 个解决方案

#1


1  

If you need to save the data to your server, then you will need server-side tools ASP.NET or PHP, as you say.

如果您需要将数据保存到服务器,那么您将需要服务器端工具ASP.NET或PHP,正如您所说。

However, you said you wanted to store the data in XML format so that you can use it later in the form. You can use the data later in the same page and put it into XML like this:

但是,您说您希望以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/

But I can't think of any reason why you would want to do that! You can use plain JavaScript or JQuery to access the values directly:

但我想不出你为什么要这样做的任何理由!您可以使用纯JavaScript或JQuery直接访问值:

JQuery:

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

JS:

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

#2


2  

Unless you are using a server side language saving data to the file system (I assume you mean that by wanting to save a XML file) is not possible. A JavaScript application has no ability to write to the file system.

除非您使用服务器端语言将数据保存到文件系统(我假设您的意思是希望保存XML文件)是不可能的。 JavaScript应用程序无法写入文件系统。

You can use HTML5's storage capabilities instead. And have a look at "How to save data from a form with HTML5 storage"

您可以使用HTML5的存储功能。并查看“如何使用HTML5存储从表单中保存数据”

#3


1  

What you are asking can only be done in server side !

您要问的只能在服务器端完成!

From your question I could understand that you are newbie to web development and I know you just want to keep the data so that you can use it later on demand

根据您的问题,我可以理解您是Web开发的新手,我知道您只想保留数据,以便以后可以按需使用

My suggestion is just keep the values in cookie or url or hidden field as XML string you better choose hidden field.

我的建议是将cookie或url或hidden字段中的值保存为XML字符串,最好选择隐藏字段。

#4


1  

This code example below will allow you to grab data from fields on the page and write them out to a txt file directly to the users local box. I am currently looking for a way to write them out to XMl for a project that I am on, but at the very least I can get the data I want written out to a text file.

下面的代码示例将允许您从页面上的字段中获取数据,并将它们直接写入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();
}

#5


0  

This javascript will trigger a file download of a form's data (for each form) when the form is submitted. It does not use XML as I do not know what your schema looks like (and I question it's usefulness whereas a form serialized string can be quickly posted using xhr).

在提交表单时,此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; }
        );
})();

Build this into a bookmarklet or whatever. But if you are looking to save yourself some typing you might want to store the value in localStorage instead of a file. You do not mention how you intent to reuse the data and it would be much easier to pull it from localStorage than to build a dynamic file uploader and make the user find the correct file.

将其构建为书签或其他任何内容。但是如果你想节省一些打字,你可能希望将值存储在localStorage而不是文件中。您没有提到如何重用数据,从localStorage中提取数据要比构建动态文件上传器并让用户找到正确的文件要容易得多。

#1


1  

If you need to save the data to your server, then you will need server-side tools ASP.NET or PHP, as you say.

如果您需要将数据保存到服务器,那么您将需要服务器端工具ASP.NET或PHP,正如您所说。

However, you said you wanted to store the data in XML format so that you can use it later in the form. You can use the data later in the same page and put it into XML like this:

但是,您说您希望以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/

But I can't think of any reason why you would want to do that! You can use plain JavaScript or JQuery to access the values directly:

但我想不出你为什么要这样做的任何理由!您可以使用纯JavaScript或JQuery直接访问值:

JQuery:

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

JS:

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

#2


2  

Unless you are using a server side language saving data to the file system (I assume you mean that by wanting to save a XML file) is not possible. A JavaScript application has no ability to write to the file system.

除非您使用服务器端语言将数据保存到文件系统(我假设您的意思是希望保存XML文件)是不可能的。 JavaScript应用程序无法写入文件系统。

You can use HTML5's storage capabilities instead. And have a look at "How to save data from a form with HTML5 storage"

您可以使用HTML5的存储功能。并查看“如何使用HTML5存储从表单中保存数据”

#3


1  

What you are asking can only be done in server side !

您要问的只能在服务器端完成!

From your question I could understand that you are newbie to web development and I know you just want to keep the data so that you can use it later on demand

根据您的问题,我可以理解您是Web开发的新手,我知道您只想保留数据,以便以后可以按需使用

My suggestion is just keep the values in cookie or url or hidden field as XML string you better choose hidden field.

我的建议是将cookie或url或hidden字段中的值保存为XML字符串,最好选择隐藏字段。

#4


1  

This code example below will allow you to grab data from fields on the page and write them out to a txt file directly to the users local box. I am currently looking for a way to write them out to XMl for a project that I am on, but at the very least I can get the data I want written out to a text file.

下面的代码示例将允许您从页面上的字段中获取数据,并将它们直接写入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();
}

#5


0  

This javascript will trigger a file download of a form's data (for each form) when the form is submitted. It does not use XML as I do not know what your schema looks like (and I question it's usefulness whereas a form serialized string can be quickly posted using xhr).

在提交表单时,此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; }
        );
})();

Build this into a bookmarklet or whatever. But if you are looking to save yourself some typing you might want to store the value in localStorage instead of a file. You do not mention how you intent to reuse the data and it would be much easier to pull it from localStorage than to build a dynamic file uploader and make the user find the correct file.

将其构建为书签或其他任何内容。但是如果你想节省一些打字,你可能希望将值存储在localStorage而不是文件中。您没有提到如何重用数据,从localStorage中提取数据要比构建动态文件上传器并让用户找到正确的文件要容易得多。