Retrieving Form Data with JavaScript/jQuery
When capturing form data, you may seek a straightforward approach that mirrors the traditional HTML-only submission method. Consider the following form:
`
`Your goal is to obtain the following JSON object from this form:
{ "foo": "1", "bar": "xxx", "this": "hi" }
However, oversimplified approaches like the following may not accurately capture all form elements (such as textareas, selects, radio buttons, and checkboxes):
$("#form input").each(function () { data[theFieldName] = theFieldValue; });
Solution: $('form').serializeArray()
Fortunately, jQuery provides the $('form').serializeArray() method, which returns an array of objects containing the name and value of each form element:
[ {"name":"foo","value":"1"}, {"name":"bar","value":"xxx"}, {"name":"this","value":"hi"} ]
Alternative Option: $('form').serialize()
If you prefer a string representation of the form data, you can use $('form').serialize(), which returns a URL-encoded string:
"foo=1&bar=xxx&this=hi"
For a live demonstration, refer to the provided jsfiddle demo.
The above is the detailed content of How to retrieve form data as a JSON object using JavaScript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!