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

How Can You Send Form Data in JSON Format?

Mary-Kate Olsen
Release: 2024-10-19 12:03:02
Original
308 people have browsed it

How Can You Send Form Data in JSON Format?

How to Send Form Data as JSON Object

When crafting HTML forms, it's often necessary to send data in a structured format such as JSON. To facilitate this, let's explore how to convert form data into a JSON object and transmit it to the server.

Convert Form Data to JSON (Client-Side)

To convert form data into a JSON object:

  1. Retrieve the form data using JavaScript's FormData object (e.g., const formData = new FormData(form)).
  2. Iterate over the form elements and extract their values into a JSON object (e.g., let json = JSON.stringify(formData.entries())).

Example:

<br><script type="text/javascript"><br>  const form = document.getElementById("myForm");</p>
<p>form.addEventListener("submit", function(e) {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">e.preventDefault();

const formData = new FormData(form);
const json = JSON.stringify(formData.entries());
Copy after login

});

Setting Headers and Sending JSON to Server (Server-Side)

Once you have the JSON string, you can send it to the server using XMLHttpRequest or any preferred network request method. Remember to set the appropriate headers for JSON data:

<br>xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');<br>

Example (Using XMLHttpRequest):


const xhr = new XMLHttpRequest();
xhr.open("POST", "myUrl", true);<br>xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');<br>xhr.send(json);

Handling Received JSON Data on Server

On the server side, you can parse the received data as a JSON object and access its properties accordingly.

Example (Using Node.js):

<br>const body = request.body.toString();<br>const data = JSON.parse(body);</p>
<p>console.log(data.first_name);<br>

The above is the detailed content of How Can You Send Form Data in JSON Format?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!