Home > Web Front-end > JS Tutorial > body text

How to retrieve form data as a JSON object using JavaScript/jQuery?

Linda Hamilton
Release: 2024-11-10 17:19:02
Original
830 people have browsed it

How to retrieve form data as a JSON object using JavaScript/jQuery?

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:

`

<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>
Copy after login

`

Your goal is to obtain the following JSON object from this form:

{
    "foo": "1",
    "bar": "xxx",
    "this": "hi"
}
Copy after login

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;
});
Copy after login

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"}
]
Copy after login

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"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template