A text must understand - Ajax and form


A way of calling background interface on Web page
JQuery provides the corresponding usage, $ ajax({content}); Add the jQuery package first.
The content part is a JS object.

type:'get',  				 //Request type: get - > call doget(), post - > call dopost();
data:req,     //The data sent is req;
url:'queryAll',		   //Interface address, relative address of the project			
datatype:'json',					//Returns the format type of the data
success :function(resp){				//Callback function, which is called when the server returns data.				

Display returned data
After Ajax submits the data and the back-end processing is completed, the callback method of success is called. At this time, the front-end page can process the returned data * * (why it is the reason of local refresh technology)**
Ajax can be encapsulated in the click time. When the button is clicked, the Ajax object is called

Example 1: query all student data

  1. Front end code
  2. JS code
function query()
type:'GET',                   //Request type: get - > call doget(), post - > call dopost();
url:'queryall',			   //Interface address, relative address of the project			
datatype:'json',					//Returns the format type of the data
success :function(resp){				//Callback function, which is called when the function returns a response.				
);        //Label of table body, label selector
var target =$(".main .content tbody");
For(var rows of result){		//Loop through each object returned.
var str="<tr>"						//Splicing of table rows.
+"<td>" +rows.id+"</td>"
target.append(str);          //After insertion, it is compiled and displayed as html on the page, and the content is a row of the table.
} //Through this method, each object can be displayed in the industry

Example 2: find some student data

  1. HTML code
    Select search display: add a text line and enter the beginning and end of the student number
  2. JS code
    Get the tags with class from and to, get their value, and then remove the spaces

    Add the data option to ajax and select the back-end interface url,
    ajax() will automatically construct the data in data into? The form from = XXX & to = YYY is appended to the URL

Chinese communication reference

When we need to pass a Chinese parameter to the background, Chinese cannot be directly placed in the URL
http://xx.x.x/QueryById?filter= Zhang
This is the encoding that the browser will convert Chinese characters into hundreds of semicolons

Conversion between Chinese and corresponding codes:
String  s = "Zhang";
String query  = URLEncoder.encode(s); 
// --> %E5%BC%A0

String query = "%E5%BC%A0";
String s = URLDecoder.decode(s);   
// -->"Zhang"

Form label

<form method="post" action="addStudent">
<input  type="text" name="id">...
<input type="submit" value="Submit">

Corresponding background servlet:
doPost() --> method="post";
addStudent–> action="addStudent";
Request.getParameter("***" ) -->name="***";

Packet capture data

The form data in Post mode is placed in the body of http to submit the data

Post and Get

Features of Http Post:
1. The first line is Post
2. The data is placed in the submitted data in the body of Http
3 Chinese still use URL encoding
Features of Http Get:
1 first line Get
2. Where is the data placed in the access path? After, separated by &
3 Chinese still use URL encoding


The front end uses json to transfer data to the back end, and the back end uses json to transfer data to the front end;


  1. Front end JS code
Function  AddStudent()
var req = {	};
req.id = $('.main .content .id').val().trim();
req.name = $('.main .content .name').val().trim();
req.phone == $('.main .content .name').val().trim();

var json  =JSON.stringify(req);

 	type :"post",
  1. Back end part code
    Convert the json data from the front end into a string, and then convert it into a jsonobject to read
String  reqText = ReadAsText(request.getInputStream(),"utf-8");
JSONObject obj = new JSONObject(reqText);
int id = obj.getInt("id");
String name = obj.getString("name");
String phone = obj.getString("phone");
public String ReadAsText( InputStream inputStream ,String charset)
ByteArrayOutputStream out = new ByteArrayOutputStream[1024*16];
Byte[] data = new byte[1024];
int n = inputStream.read(data);
String str = out.toString(charset);
return str;

Restful comes with URL parameters

  1. Front end JS
function  addStudent()
var req = {	};
req.id = $('.main .content .id').val().trim();
req.name = $('.main .content .name').val().trim();
req.phone == $('.main .content .name').val().trim();

var json  =JSON.stringify(req);

type :"post",
  1. back-end
//----------Servlet doPost method------
HashMap<String ,String> map = queryString(request.getQueryString());
Public HashMap<String ,String> queryString(String queryString){
HashMap<String,String> map = new HashMap<String,String>();
String[] ppp= queryString.split("&");
While(String p :ppp)
String[] kv = p.split("=");
String key = kv[0];
String value = kv[1];

Ajax and form tags

Why does the front end use ajax and rarely use the form tag to submit requests?

  • Interaction mode:
  1. The synchronization method used by the form, that is, after clicking the submit button, the data will be submitted to the back-end interface. The front-end cannot receive the data returned by the back-end.
  2. The asynchronous method used by ajax, that is, after clicking the submit button, after the data is submitted to the back-end interface, and after the back-end returns the data, the success asynchronous call method of the front-end can accept the data returned by the back-end, and then use JS to refresh the data in some places. (e.g. not logged in – > logged in);
  • Data processing format
    When using the form tag to submit data, it is difficult to convert it into JSON format data;
    When submitting data in Ajax, you only need to convert the data format in JS function.

Keywords: Java Javascript JQuery Ajax

Added by Stelios on Wed, 09 Feb 2022 11:13:29 +0200