是否有一种简单的单行方式来获取表单的数据,就像以经典的仅html方式提交表单一样?

例如:

<form>
    <input type="radio" name="foo" value="1" checked="checked" />
    <input type="radio" name="foo" value="0" />
    <input name="bar" value="xxx" />
    <select name="this">
        <option value="hi" selected="selected">Hi</option>
        <option value="ho">Ho</option>
</form>

输出:

{
    "foo": "1",
    "bar": "xxx",
    "this": "hi"
}

像这样的东西太简单了,因为它没有(正确地)包括文本区域,选择,单选按钮和复选框:

$("#form input").each(function () {
    data[theFieldName] = theFieldValue;
});

当前回答

显示表单输入元素字段和输入文件提交您的表单没有页面刷新和抓取所有值与文件包括在这里

<form id="imageUploadForm" action="" method="post" enctype="multipart/form-data"> <input type="text" class="form-control" id="fname" name='fname' placeholder="First Name" > <input type="text" class="form-control" name='lname' id="lname" placeholder="Last Name"> <input type="number" name='phoneno' class="form-control" id="phoneno" placeholder="Phone Number"> <textarea class="form-control" name='address' id="address" rows="5" cols="5" placeholder="Your Address"></textarea> <input type="file" name="file" id="file" > <input type="submit" id="sub" value="Registration"> </form> on Submit button page will send ajax request to your php file. $('#imageUploadForm').on('submit',(function(e) { fname = $('#fname').val(); lname = $('#lname').val(); address = $('#address').val(); phoneno = $('#phoneno').val(); file = $('#file').val(); e.preventDefault(); var formData = new FormData(this); formData.append('file', $('#file')[0]); formData.append('fname',$('#fname').val()); formData.append('lname',$('#lname').val()); formData.append('phoneno',$('#phoneno').val()); formData.append('address',$('#address').val()); $.ajax({ type:'POST', url: "test.php", //url: '<?php echo base_url().'edit_profile/edit_profile2';?>', data:formData, cache:false, contentType: false, processData: false, success:function(data) { alert('Data with file are submitted !'); } }); }))

其他回答

你也可以使用FormData对象;FormData对象允许您编译一组键/值对,以便使用XMLHttpRequest发送。它主要用于发送表单数据,但也可以独立于表单用于传输键控数据。

        var formElement = document.getElementById("myform_id");
        var formData = new FormData(formElement);
        console.log(formData);

这里有一个非常简单和简短的解决方案,甚至不需要Jquery。

var formElements=document.getElementById("myForm").elements;    
var postData={};
for (var i=0; i<formElements.length; i++)
    if (formElements[i].type!="submit")//we dont want to include the submit-buttom
        postData[formElements[i].name]=formElements[i].value;

这是一个很好的香草JS函数,我写来提取表单数据作为一个对象。它还具有向对象中插入附加内容和清除表单输入字段的选项。

const extractFormData = ({ form, clear, add }) => {
  return [].slice.call(form.children).filter(node => node.nodeName === 'INPUT')
  .reduce((formData, input) => {
    const value = input.value
    if (clear) { input.value = '' }
    return {
      ...formData,
      [input.name]: value
    }
  }, add)
}

下面是一个使用post请求的例子:

submitGrudge(e) {
  e.preventDefault()

  const form = e.target
  const add = { id: Date.now(), forgiven: false }
  const grudge = extractFormData({ form, add, clear: true })

  // grudge = {
  //  "name": "Example name",
  //  "offense": "Example string",
  //  "date": "2017-02-16",
  //  "id": 1487877281983,
  //  "forgiven": false
  // }

  fetch('http://localhost:3001/api/grudge', {
    method: 'post',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(grudge)
  })
    .then(response => response.json())
    .then(grudges => this.setState({ grudges }))
    .catch(err => console.log('error: ', err))
}
document.querySelector('form').addEventListener('submit', (e) => {
  const formData = new FormData(e.target);
  // Now you can use formData.get('foo'), for example.
  // Don't forget e.preventDefault() if you want to stop normal form .submission
});

这是一个吹毛求疵的答案,但让我解释为什么这是一个更好的解决方案:

We're properly handling a form submit rather than a button press. Some people like to push enter on fields. Some people use alternative input devices such as speech input or other accessibility devices. Handle the form submit and you correctly solve it for everyone. We're digging into the form data for the actual form that was submitted. If you change your form selector later, you don't have to change the selectors for all the fields. Furthermore, you might have several forms with the same input names. No need to disambiguate with excessive IDs and what not, just track the inputs based on the form that was submitted. This also enables you to use a single event handler for multiple forms if that is appropriate for your situation. The FormData interface is fairly new, but is well supported by browsers. It's a great way to build that data collection to get the real values of what's in the form. Without it, you're going to have to loop through all the elements (such as with form.elements) and figure out what's checked, what isn't, what the values are, etc. Totally possible if you need old browser support, but the FormData interface is simpler. I'm using ES6 here... not a requirement by any means, so change it back to be ES5 compatible if you need old browser support.

使用.serializeArray()获取数组格式的数据,然后将其转换为对象:

function getFormObj(formId) {
    var formObj = {};
    var inputs = $('#'+formId).serializeArray();
    $.each(inputs, function (i, input) {
        formObj[input.name] = input.value;
    });
    return formObj;
}