Home Web Front-end JS Tutorial Detailed steps to submit data to the server using JSON

Detailed steps to submit data to the server using JSON

Apr 20, 2018 pm 02:37 PM
javascript json Serve

This time I will bring you a detailed step-by-step explanation of using JSON to submit data to the server. What are the precautions for using JSON to submit data to the server? The following is a practical case, let's take a look.

Prepare Hero.java

public class Hero { 
 private String name; 
 private int hp; 
 public String getName() { 
  return name; 
 }  public void setName(String name) { 
  this.name = name; 
 } 
 public int getHp() { 
  return hp; 
 } 
 public void setHp(int hp) { 
  this.hp = hp; 
 } 
 @Override 
  public String toString() { 
   return "Hero [name=" + name + ", hp=" + hp + "]"; 
  } 
} 
public class Hero {
 private String name;
 private int hp;
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public int getHp() {
 return hp;
 }
 public void setHp(int hp) {
 this.hp = hp;
 }
 @Override
 public String toString() {
   return "Hero [name=" + name + ", hp=" + hp + "]";
  }
}submit.html文件
[html] view plain copy print?<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>用AJAX以JSON方式提交数据</title> 
<script type="text/javascript" src="jquery.min.js"></script> 
</head> 
<body> 
 <form > 
  名称:<input type="text" id="name"/><br/> 
  血量:<input type="text" id="hp"/><br/> 
  <input type="button" value="提交" id="sender">  
 </form> 
 <p id="messagep"></p> 
 <script> 
 $('#sender').click(function(){ 
  var name=document.getElementById('name').value; 
  var hp=document.getElementById('hp').value; 
  var hero={"name":name,"hp":hp}; 
  var url="submitServlet"; 
  $.post( 
    url, 
    {"data":JSON.stringify(hero)}, 
    function(data) { 
      alert("提交成功,请在Tomcat控制台查看服务端接收到的数据"); 
   });  
 }); 
 </script> 
</body> 
</body> 
</html> 
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>用AJAX以JSON方式提交数据</title> 
<script type="text/javascript" src="jquery.min.js"></script> 
</head> 
<body> 
 <form > 
  名称:<input type="text" id="name"/><br/> 
  血量:<input type="text" id="hp"/><br/> 
  <input type="button" value="提交" id="sender"> 
 </form> 
 <p id="messagep"></p> 
 <script> 
 $('#sender').click(function(){ 
  var name=document.getElementById('name').value; 
  var hp=document.getElementById('hp').value; 
  var hero={"name":name,"hp":hp}; 
  var url="submitServlet"; 
  $.post(
   url, 
   {"data":JSON.stringify(hero)},
   function(data) { 
    alert("提交成功,请在Tomcat控制台查看服务端接收到的数据");
   }); 
 }); 
 </script> 
</body> 
</body>
</html>
Copy after login

The function of JSON.stringify function is to convert a javascript object into a string in JSON format.

Prepare SubmitServlet to receive data

import java.io.IOException; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import net.sf.json.JSONObject; 
public class SubmitServlet extends HttpServlet { 
 protected void service(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException { 
  String data =request.getParameter("data"); 
  System.out.println("服务端接收到的数据是:" +data); 
  JSONObject json=JSONObject.fromObject(data); 
  System.out.println("转换为JSON对象之后是:"+ json); 
  Hero hero = (Hero)JSONObject.toBean(json,Hero.class); 
  System.out.println("转换为Hero对象之后是:"+hero); 
 } 
} 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject; 
public class SubmitServlet extends HttpServlet { 
 protected void service(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException {
  String data =request.getParameter("data");
  System.out.println("服务端接收到的数据是:" +data);
  JSONObject json=JSONObject.fromObject(data); 
  System.out.println("转换为JSON对象之后是:"+ json);
  Hero hero = (Hero)JSONObject.toBean(json,Hero.class); 
  System.out.println("转换为Hero对象之后是:"+hero);
 } 
}
Copy after login

1. Get the string submitted by the browser

2. Convert the string into a JSON object

3 . Convert JSON object to Hero object

Finally configure web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<web-app> 
  <servlet> 
  <servlet-name>SubmitServlet</servlet-name> 
  <servlet-class>SubmitServlet</servlet-class> 
 </servlet> 
 <servlet-mapping> 
  <servlet-name>SubmitServlet</servlet-name> 
  <url-pattern>/submitServlet</url-pattern> 
 </servlet-mapping> 
</web-app> 
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
 <servlet>
  <servlet-name>SubmitServlet</servlet-name>
  <servlet-class>SubmitServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>SubmitServlet</servlet-name>
  <url-pattern>/submitServlet</url-pattern>
 </servlet-mapping>
Copy after login

Start tomcat to access http://127.0.0.1:8080/project name/submit .html

See the transmitted data in the tomcat console

I believe you have mastered it after reading the case in this article For more exciting methods, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps for calling child components from Angular parent components

Detailed explanation of vue axios request timeout processing (attached Code)

The above is the detailed content of Detailed steps to submit data to the server using JSON. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

What is the correct way to restart a service in Linux? What is the correct way to restart a service in Linux? Mar 15, 2024 am 09:09 AM

What is the correct way to restart a service in Linux? When using a Linux system, we often encounter situations where we need to restart a certain service, but sometimes we may encounter some problems when restarting the service, such as the service not actually stopping or starting. Therefore, it is very important to master the correct way to restart services. In Linux, you can usually use the systemctl command to manage system services. The systemctl command is part of the systemd system manager

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Solution to Ubuntu PHP service failing to start normally Solution to Ubuntu PHP service failing to start normally Feb 28, 2024 am 10:48 AM

Title: Methods and specific code examples to solve the problem that the PHP service cannot start normally under Ubuntu. When using Ubuntu to build a website or application, you often encounter the problem that the PHP service cannot start normally, which will cause the website to be unable to be accessed normally or the application to be unable to function normally. run. This article will introduce how to solve the problem that the PHP service cannot start normally under Ubuntu, and provide specific code examples to help readers quickly solve such failures. 1. Check the PHP configuration file First, we need to check the PHP configuration file

In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese Mar 05, 2024 pm 02:48 PM

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

How to execute service restart command in Linux? How to execute service restart command in Linux? Mar 14, 2024 am 11:06 AM

In Linux, to execute the service restart command, you usually need to use the Systemd service manager. Systemd is a widely used service management tool on Linux, which can easily manage and control system services. The following will introduce how to execute the service restart command through Systemd in Linux and provide specific code examples. Step 1: Confirm the service name. Before executing the service restart command, you first need to confirm the name of the service to be restarted. You can view the list of services running on the system with the following command:

PHP Tutorial: How to Convert JSON Unicode to Chinese Characters PHP Tutorial: How to Convert JSON Unicode to Chinese Characters Mar 05, 2024 pm 06:36 PM

JSON (JavaScriptObjectNotation) is a lightweight data exchange format commonly used for data exchange between web applications. When processing JSON data, we often encounter Unicode-encoded Chinese characters (such as "u4e2du6587") and need to convert them into readable Chinese characters. In PHP, we can achieve this conversion through some simple methods. Next, we will detail how to convert JSONUnico

See all articles