Wondering is there a function in javascript without jquery or any framework that allows me to serialize the form and access the serialize version?
相关问题
- Is there a limit to how many levels you can nest i
- Laravel Option Select - Default Issue
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
This miniature library doesn't rely on a framework. Other than something like that, you'll need to implement the serialization function yourself. (though at a weight of 1.2 kilobytes, why not use it?)
If you need to submit form "myForm" using POST in json format you can do:
The second line converts from an array like:
...into a regular object, like:
...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?
Source: http://code.google.com/p/form-serialize/source/browse/trunk/serialize-0.1.js
A refactored version of @SimonSteinberger's code using less variables and taking advantage of the speed of
forEach
loops (which are a bit faster thanfor
s)