How can I get form data with JavaScript/jQuery?

前端 未结 28 2222
不知归路
不知归路 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条回答
  •  Happy的楠姐
    2020-11-22 13:22

    You are all not fully correct. You cannot write:

    formObj[input.name] = input.value;
    

    Because this way if you have multiselect list - its values will be overwritten with the last one, since it's transmitted as: "param1" : "value1", "param1" : "value2".

    So, correct approach is:

    if (formData[input.name] === undefined) {
        formData[input.name] = input.value;
    }
    else {
        var inputFieldArray = $.merge([], $.isArray(formData[input.name]) ? formData[input.name] : [formData[input.name]]);
        $.merge(inputFieldArray, [input.value]);
        formData[input.name] = $.merge([], inputFieldArray);
    }
    

提交回复
热议问题