js实现表单序列化的两种方法。

 

function serialize(form) {
    var parts = [],
            elems = form.elements,
            i = 0,
            len = elems.length,
            filed = null;
    for (; i < len; i++) {
        filed = elems[i];
        switch (filed.type) {
            case "select-one":
            case "select-multiple":
                if (filed.name.length) {
                    var j = 0,
                            opt,
                            optLen = filed.options.length;
                    for (; j < optLen; j++) {
                        opt = filed.options[j];
                        if (opt.selected) {
                            parts.push(encodeURIComponent(filed.name) + "=" + encodeURIComponent(opt.value));
                        }
                    }
                }
                break;
            case undefined:
            case "submit":
            case "reset":
            case "file":
            case "button":
                break;
            case "radio":
            case "checkbox":
                if (!filed.checked) {
                    break;
                }
            default:
                if (filed.name.length && filed.value) {
                    parts.push(encodeURIComponent(filed.name) + "=" + encodeURIComponent(filed.value));
                }
        }
    }
    return parts.join("&");
}

 

 这个方法重点用了HTML5中的FormData ,还有es6中for of循环。

  function serialize(form) {
        var formData = new FormData(form),
            getValue = formData.entries(),
            parts = [];
        for (var pair of getValue) {
            parts.push(pair[0] + "=" + pair[1]);
        }
        return parts.join("&");
    }

 

posted @ 2016-12-07 11:26  赵小磊  阅读(3226)  评论(0编辑  收藏  举报
回到头部