form serialize javascript (no framework)

后端 未结 23 1386
一生所求
一生所求 2020-11-22 16:07

Wondering is there a function in javascript without jquery or any framework that allows me to serialize the form and access the serialized version?

相关标签:
23条回答
  • 2020-11-22 17:07

    If you need to submit form "myForm" using POST in json format you can do:

    const formEntries = new FormData(myForm).entries();
    const json = Object.assign(...Array.from(formEntries, ([x,y]) => ({[x]:y})));
    fetch('/api/foo', {
      method: 'POST',
      body: JSON.stringify(json)
    });
    

    The second line converts from an array like:

    [["firstProp", "firstValue"], ["secondProp", "secondValue"], ...and so on... ]
    

    ...into a regular object, like:

    {"firstProp": "firstValue", "secondProp": "secondValue", ...and so on ... }
    

    ...it does this conversion by passing in a mapFn into Array.from(). This mapFn is applied to each ["a","b"] pair and converts them into {"a": "b"} so that the array contains a lot of object with only one property in each. The mapFn is using "destructuring" to get names of the first and second parts of the pair, and it is also using an ES6 "ComputedPropertyName" to set the property name in the object returned by the mapFn (this is why is says "[x]: something" rather than just "x: something".

    All of these single property objects are then passed into arguments of the Object.assign() function which merges all the single property objects into a single object that has all properties.

    Array.from(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

    Destructuring in parameters: https://simonsmith.io/destructuring-objects-as-function-parameters-in-es6/

    More on computed property names here: Variable as the property name in a JavaScript object literal?

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

    I hope this will work

    var serializeForm = (formElement) => {
      const formData = {};
      const inputs = formElement.elements;
    
      for (let i = 0; i < inputs.length; i++) {
        if(inputs[i].name!=="")
            formData[inputs[i].name] = inputs[i].value;
      }
      return formData;
    }
    
    0 讨论(0)
  • 2020-11-22 17:07

    my way...

    const myForm = document.forms['form-name']
    
    myForm.onsubmit=e=>
      {
      e.preventDefault()  // for testing...
    
      let data = Array.from(new FormData(myForm))
                      .reduce((r,[k,v])=>{r[k]=v;return r},{})
    
      /*_______________________________________ same code: for beginners 
      let data = {}
      Array.from(new FormData(myForm), (entry) => { data[ entry[0] ] = entry[1]} )
      ________________________________________________________________*/
     
      console.log(data)
      
      //...
      }
    
    0 讨论(0)
  • 2020-11-22 17:08

    Here is pure JavaScript approach:

    var form = document.querySelector('form');
    var data = new FormData(form);
    
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
           console.log(this.responseText);
        }
      };
      xhttp.open("POST", "<YOUR-URL>", true);
      xhttp.send(data);
    }
    
    0 讨论(0)
  • 2020-11-22 17:08

    I could be crazy but I'm finding these answers seriously bloated. Here's my solution

    function serialiseForm(form) {
      var input = form.getElementsByTagName("input");
      var formData = {};
      for (var i = 0; i < input.length; i++) {
        formData[input[i].name] = input[i].value;
      }
      return formData = JSON.stringify(formData);
    }
    
    0 讨论(0)
提交回复
热议问题