How can I get form data with JavaScript/jQuery?

前端 未结 28 1871
不知归路
不知归路 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:06
    $('form').serialize() //this produces: "foo=1&bar=xxx&this=hi"
    

    demo

    0 讨论(0)
  • 2020-11-22 13:08

    You can also use the FormData Objects; The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data.

            var formElement = document.getElementById("myform_id");
            var formData = new FormData(formElement);
            console.log(formData);
    
    0 讨论(0)
  • 2020-11-22 13:09

    Here is a nice vanilla JS function I wrote to extract form data as an object. It also has options for inserting additions into the object, and for clearing the form input fields.

    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)
    }
    

    Here is an example of its use with a post request:

    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))
    }
    
    0 讨论(0)
  • 2020-11-22 13:12

    This will append all form fields to the JavaScript object "res":

    var res = {};
    $("#form input, #form select, #form textarea").each(function(i, obj) {
        res[obj.name] = $(obj).val();
    })
    
    0 讨论(0)
  • 2020-11-22 13:14

    Use $('form').serializeArray(), which returns an array:

    [
      {"name":"foo","value":"1"},
      {"name":"bar","value":"xxx"},
      {"name":"this","value":"hi"}
    ]
    

    Other option is $('form').serialize(), which returns a string:

    "foo=1&bar=xxx&this=hi"
    

    Take a look at this jsfiddle demo

    0 讨论(0)
  • 2020-11-22 13:17

    Based on jQuery.serializeArray, returns key-value pairs.

    var data = $('#form').serializeArray().reduce(function(obj, item) {
        obj[item.name] = item.value;
        return obj;
    }, {});
    
    0 讨论(0)
提交回复
热议问题