How can I get form data with JavaScript/jQuery?

前端 未结 28 1932
不知归路
不知归路 2020-11-22 12:39

Is there a simple, one-line way to get the data of a form as it would be if it was to be submitted in the classic HTML-only way?

For example:



        
28条回答
  •  死守一世寂寞
    2020-11-22 13:27

    I wrote a function that takes care of multiple checkboxes and multiple selects. In those cases it returns an array.

    function getFormData(formId) {
        return $('#' + formId).serializeArray().reduce(function (obj, item) {
            var name = item.name,
                value = item.value;
    
            if (obj.hasOwnProperty(name)) {
                if (typeof obj[name] == "string") {
                    obj[name] = [obj[name]];
                    obj[name].push(value);
                } else {
                    obj[name].push(value);
                }
            } else {
                obj[name] = value;
            }
            return obj;
        }, {});
    }
    

提交回复
热议问题