How can I get form data with JavaScript/jQuery?

前端 未结 28 1870
不知归路
不知归路 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:19

    This method should do it. It serializes the form data and then converts them to an object. Takes care of groups of checkboxes as well.

    function getFormObj(formId) {
      var formParams = {};
      $('#' + formId)
        .serializeArray()
        .forEach(function(item) {
          if (formParams[item.name]) {
            formParams[item.name] = [formParams[item.name]];
            formParams[item.name].push(item.value)
          } else {
            formParams[item.name] = item.value
          }
        });
      return formParams;
    }
    

提交回复
热议问题