Home >Web Front-end >JS Tutorial >How to Transmit HTML Form Data as JSON Using Ajax?
In the realm of web development, often arises the need to transmit data from an HTML form to a server. While traditional methods exist, this article explores an alternative approach: sending the form data as a JSON object.
The Challenge
Suppose you have an HTML form with the following structure:
<code class="html"><form action="myurl" method="POST" name="myForm"> <label for="first_name">First Name:</label> <input type="text" name="first_name" id="fname"> <label for="last_name">Last Name:</label> <input type="text" name="last_name" id="lname"> <input value="Submit" type="submit" onclick="submitform()"> </form></code>
The objective is to send the data entered into this form as a JSON object when the user clicks the "Submit" button.
Initial Error
Some may attempt to use this code:
<code class="javascript">var j = { "first_name":"binchen", "last_name":"heris", }; xhr.send(JSON.stringify(j));</code>
However, this approach fails because it doesn't retrieve the actual data from the form inputs.
解决方案
The key to solving this issue lies in obtaining the complete form data. This can be achieved using the following code:
<code class="javascript">var formData = JSON.stringify($("#myForm").serializeArray());</code>
The serializeArray() method converts the form data into an array of key-value pairs. By converting this array to a JSON string, we can obtain the desired JSON object.
Integration with Ajax
To transmit the JSON data using Ajax, you can use the following code:
<code class="javascript">$.ajax({ type: "POST", url: "serverUrl", data: formData, success: function(){}, dataType: "json", contentType: "application/json" });</code>
Now, when a user submits the form, the JSON object containing the form data will be sent to the specified server URL via Ajax.
This approach provides a convenient and efficient way to send HTML form data as a JSON object, enhancing the versatility and functionality of your web applications.
The above is the detailed content of How to Transmit HTML Form Data as JSON Using Ajax?. For more information, please follow other related articles on the PHP Chinese website!