Jquery greatly simplifies Ajax development and makes Ajax applications necessary for front-end and back-end data transmission. Generally, we can use a normal string as the data transmitted in the front and back ends (for example, we can use special characters to separate each element and use split to process it in the background ). When the amount of data transmitted is large or the data format is complex, we can consider using JSON or XML format to encapsulate and transmit data.
Jquery's Ajax functions are very good. We can call the encapsulated $. get (), $. post (), $. ajax (), the first two functions are special for the last function, that is, $. ajax () makes our Ajax journey more manageable.
The following is a simple example of JSON transmission:
import org.json.*; public class MyBean { private String name; private int num; private int array[]; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public int[] getArray() { return array; } public void setArray(int[] array) { this.array = array; } public JSONObject toJson() { JSONObject obj; try { obj= new JSONObject(); obj.put("name", this.name); obj.put("num", this.num); JSONArray array = new JSONArray(this.array); obj.put("array", array); } catch (Exception e) { e.printStackTrace(); return null; } return obj; } }
It is just a simple pojo class used for simulation. It has its own tojson () method. Org. JSON package is required
import java.io.IOException; import java.io.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class JsonServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub this.doGet(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub MyBean b = new MyBean(); b.setNum(22); b.setName("andrew"); int [] array={1,2,3,4}; b.setArray(array); String str=(String)request.getParameter("text"); System.out.println(str); PrintWriter out=response.getWriter(); String data=b.toJson().toString(); out.print(data); System.out.println(data); out.flush(); } }
Servlet that accepts Ajax requests
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
The $. Post () method is used to transmit JSON data. The last parameter of the method is set to accept JSON data by default.