form serialize javascript (no framework)

2019-01-01 08:53发布

Wondering is there a function in javascript without jquery or any framework that allows me to serialize the form and access the serialize version?

17条回答
ら面具成の殇う
2楼-- · 2019-01-01 09:13

I started with the answer from Johndave Decano.

This should fix a few of the issues mentioned in replies to his function.

  1. Replace %20 with a + symbol.
  2. Submit/Button types will only be submitted if they were clicked to submit the form.
  3. Reset buttons will be ignored.
  4. The code seemed redundant to me since it is doing essentially the same thing regardless of the field types. Not to mention incompatibility with HTML5 field types such as 'tel' and 'email', thus I removed most of the specifics with the switch statements.

Button types will still be ignored if they don't have a name value.

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

This is how I am currently using this function.

<form onsubmit="myAjax('http://example.com/services/email.php', 'POST', serialize(this, event))">
查看更多
几人难应
3楼-- · 2019-01-01 09:14
  // supports IE8 and IE9 
  function serialize(form) {
    var inputs = form.elements;
    var array = [];
    for(i=0; i < inputs.length; i++) {
      var inputNameValue = inputs[i].name + '=' + inputs[i].value;
      array.push(inputNameValue);
    }
    return array.join('&');
  }
 //using the serialize function written above
 var form = document.getElementById("form");//get the id of your form. i am assuming the id to be named form.
 var form_data = serialize(form);
 var xhr = new XMLHttpRequest();
 xhr.send(form_data);

 //does not work with IE8 AND IE9
 var form = document.querySelector('form');
 var data = new FormData(form);
 var xhr = new XMLHttpRequest();
 xhr.send(data);
查看更多
步步皆殇っ
4楼-- · 2019-01-01 09:15

I refactored TibTibs answer into something that's much clearer to read. It is a bit longer because of the 80 character width and a few comments.

Additionally, it ignores blank field names and blank values.

// Serialize the specified form into a query string.
//
// Returns a blank string if +form+ is not actually a form element.
function $serialize(form, evt) {
  if(typeof(form) !== 'object' && form.nodeName !== "FORM")
    return '';

  var evt    = evt || window.event || { target: null };
  evt.target = evt.target || evt.srcElement || null;
  var field, query = '';

  // Transform a form field into a query-string-friendly
  // serialized form.
  //
  // [NOTE]: Replaces blank spaces from its standard '%20' representation
  //         into the non-standard (though widely used) '+'.
  var encode = function(field, name) {
    if (field.disabled) return '';

    return '&' + (name || field.name) + '=' +
           encodeURIComponent(field.value).replace(/%20/g,'+');
  }

  // Fields without names can't be serialized.
  var hasName = function(el) {
    return (el.name && el.name.length > 0)
  }

  // Ignore the usual suspects: file inputs, reset buttons,
  // buttons that did not submit the form and unchecked
  // radio buttons and checkboxes.
  var ignorableField = function(el, evt) {
    return ((el.type == 'file' || el.type == 'reset')
        || ((el.type == 'submit' || el.type == 'button') && evt.target != el)
        || ((el.type == 'checkbox' || el.type == 'radio') && !el.checked))
  }

  var parseMultiSelect = function(field) {
    var q = '';

    for (var j=field.options.length-1; j>=0; j--) {
      if (field.options[j].selected) {
        q += encode(field.options[j], field.name);
      }
    }

    return q;
  };

  for(i = form.elements.length - 1; i >= 0; i--) {
    field = form.elements[i];

    if (!hasName(field) || field.value == '' || ignorableField(field, evt))
      continue;

    query += (field.type == 'select-multiple') ? parseMultiSelect(field)
                                               : encode(field);
  }

  return (query.length == 0) ? '' : query.substr(1);
}
查看更多
笑指拈花
5楼-- · 2019-01-01 09:17

Here is pure JavaScript approach:

var form = document.querySelector('form');
var data = new FormData(form);
var req = new XMLHttpRequest();
req.send(data);

Though it seems to be working only for POST requests.

https://developer.mozilla.org/en-US/docs/Web/API/FormData

查看更多
永恒的永恒
6楼-- · 2019-01-01 09:18

If you target browsers that support the URLSearchParams API (all recent browsers), use this:

new URLSearchParams(new FormData(formElement)).toString()

Otherwise, use this one-liner (works everywhere except IE):

Array.from(new FormData(formElement), e => e.map(encodeURIComponent).join('=')).join('&')
查看更多
与风俱净
7楼-- · 2019-01-01 09:19

I've grabbed the entries() method of formData from @moison answer and from MDN it's said that :

The FormData.entries() method returns an iterator allowing to go through all key/value pairs contained in this object. The key of each pair is a USVString object; the value either a USVString, or a Blob.

but the only issue is that mobile browser (android and safari are not supported ) and IE and Safari desktop too

but basically here is my approach :

let theForm =  document.getElementById("contact"); 

theForm.onsubmit = function(event) {
    event.preventDefault();

    let rawData = new FormData(theForm);
    let data = {};

   for(let pair of rawData.entries()) {
     data[pair[0]] = pair[1]; 
    }
    let contactData = JSON.stringify(data);
    console.warn(contactData);
    //here you can send a post request with content-type :'application.json'

};

the code can be found here

查看更多
登录 后发表回答