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:21
document.serializeForm = function (selector) {
     var dictionary = {};
     var form = document.querySelector(selector);
     var formdata = new FormData(form);
     var done = false;
     var iterator = formdata.entries();
     do {
         var prop = iterator.next();
         if (prop.done && !prop.value) {
             done = true;
         }
         else {
             dictionary[prop.value[0]] = prop.value[1];
         }

     } while (!done);
     return dictionary;
}
查看更多
临风纵饮
3楼-- · 2019-01-01 09:22

This miniature library doesn't rely on a framework. Other than something like that, you'll need to implement the serialization function yourself. (though at a weight of 1.2 kilobytes, why not use it?)

查看更多
公子世无双
4楼-- · 2019-01-01 09:23

If you need to submit form "myForm" using POST in json format you can do:

const formEntries = new FormData(myForm).entries();
const json = Object.assign(...Array.from(formEntries, ([x,y]) => ({[x]:y})));
fetch('/api/foo', {
  method: 'POST',
  body: JSON.stringify(json)
});

The second line converts from an array like:

[["firstProp", "firstValue"], ["secondProp", "secondValue"], ...and so on... ]

...into a regular object, like:

{"firstProp": "firstValue", "secondProp": "secondValue", ...and so on ... }

...it does this conversion by passing in a mapFn into Array.from(). This mapFn is applied to each ["a","b"] pair and converts them into {"a": "b"} so that the array contains a lot of object with only one property in each. The mapFn is using "destructuring" to get names of the first and second parts of the pair, and it is also using an ES6 "ComputedPropertyName" to set the property name in the object returned by the mapFn (this is why is says "[x]: something" rather than just "x: something".

All of these single property objects are then passed into arguments of the Object.assign() function which merges all the single property objects into a single object that has all properties.

Array.from(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

Destructuring in parameters: https://simonsmith.io/destructuring-objects-as-function-parameters-in-es6/

More on computed property names here: Variable as the property name in a JavaScript object literal?

查看更多
妖精总统
5楼-- · 2019-01-01 09:24

const inputs = document.querySelector("form").elements;
const values = {};

for (let i = 0; i < inputs.length; i++) {
  values[inputs[i].name] = inputs[i].value;
}
console.log(values);
console.log(JSON.stringify(values));
<form action="/my-handling-form-page" method="post">
  <div>
    <label for="name">Name:</label>
    <input type="text" id="name" name="user_name" value="John">
  </div>
  <div>
    <label for="mail">E-mail:</label>
    <input type="email" id="mail" name="user_mail" value="john@jonhson.j">
  </div>
  <div>
    <label for="msg">Message:</label>
    <textarea id="msg" name="user_message">Hello My Friend</textarea>
  </div>
</form>

查看更多
琉璃瓶的回忆
6楼-- · 2019-01-01 09:25
function serialize (form) {
    if (!form || form.nodeName !== "FORM") {
            return;
    }
    var i, j, q = [];
    for (i = form.elements.length - 1; i >= 0; i = i - 1) {
        if (form.elements[i].name === "") {
            continue;
        }
        switch (form.elements[i].nodeName) {
            case 'INPUT':
                switch (form.elements[i].type) {
                    case 'text':
                    case 'tel':
                    case 'email':
                    case 'hidden':
                    case 'password':
                    case 'button':
                    case 'reset':
                    case 'submit':
                        q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                        break;
                    case 'checkbox':
                    case 'radio':
                        if (form.elements[i].checked) {
                                q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                        }                                               
                        break;
                }
                break;
                case 'file':
                break; 
            case 'TEXTAREA':
                    q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                    break;
            case 'SELECT':
                switch (form.elements[i].type) {
                    case 'select-one':
                        q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                        break;
                    case 'select-multiple':
                        for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
                            if (form.elements[i].options[j].selected) {
                                    q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
                            }
                        }
                        break;
                }
                break;
            case 'BUTTON':
                switch (form.elements[i].type) {
                    case 'reset':
                    case 'submit':
                    case 'button':
                        q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                        break;
                }
                break;
            }
        }
    return q.join("&");
}

Source: http://code.google.com/p/form-serialize/source/browse/trunk/serialize-0.1.js

查看更多
初与友歌
7楼-- · 2019-01-01 09:30

A refactored version of @SimonSteinberger's code using less variables and taking advantage of the speed of forEach loops (which are a bit faster than fors)

function serialize(form) {
    var result = [];
    if (typeof form === 'object' && form.nodeName === 'FORM')
        Array.prototype.slice.call(form.elements).forEach(function(control) {
            if (
                control.name && 
                !control.disabled && 
                ['file', 'reset', 'submit', 'button'].indexOf(control.type) === -1
            )
                if (control.type === 'select-multiple')
                    Array.prototype.slice.call(control.options).forEach(function(option) {
                        if (option.selected) 
                            result.push(encodeURIComponent(control.name) + '=' + encodeURIComponent(option.value));
                    });
                else if (
                    ['checkbox', 'radio'].indexOf(control.type) === -1 || 
                    control.checked
                ) result.push(encodeURIComponent(control.name) + '=' + encodeURIComponent(control.value));
        });
        return result.join('&').replace(/%20/g, '+');
}
查看更多
登录 后发表回答