form serialize javascript (no framework)

后端 未结 23 1552
一生所求
一生所求 2020-11-22 16:07

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

23条回答
  •  一个人的身影
    2020-11-22 16:41

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

提交回复
热议问题