简体   繁体   中英

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

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

<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.

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.

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

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

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

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

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:

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:

JQuery:

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

JS:

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

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.

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();
}

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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