form serialize javascript (no framework)

后端 未结 23 1546
一生所求
一生所求 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 17:07

    Here's a slightly modified version of TibTibs':

    function serialize(form) {
        var field, s = [];
        if (typeof form == 'object' && form.nodeName == "FORM") {
            var len = form.elements.length;
            for (i=0; i=0; j--) {
                            if(field.options[j].selected)
                                s[s.length] = encodeURIComponent(field.name) + "=" + encodeURIComponent(field.options[j].value);
                        }
                    } else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) {
                        s[s.length] = encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value);
                    }
                }
            }
        }
        return s.join('&').replace(/%20/g, '+');
    }
    

    Disabled fields are discarded and names are also URL encoded. Regex replace of %20 characters takes place only once, before returning the string.

    The query string is in identical form to the result from jQuery's $.serialize() method.

提交回复
热议问题