1. Definitions
AJAX: asynchronous JavaScript and xml are not new programming. It refers to an interactive method, asynchronous loading, and the technology of interactive updating of data between client and server on local pages. There is no need to refresh the whole page (local refresh)
1.1 advantages
- Local refresh, better effect
- Better user experience
2. AJAX based on jQuery
2.1 grammar
$.ajax({attribute})
Common attribute parameters:
- url: the requested back-end service address
- Type: request type. The default is get
- data: request parameters
- dataType: the data type returned by the server, text/json
- success: callback function for successful request
- error: callback function for request failure
- complete: the callback function that requests completion (it will be called back whether it succeeds or fails)
2.2 JSON
A lightweight data interaction format, which completes the conversion between object data of back-end development languages such as js and java
The transfer of object data between client and server requires JSON format
var user = { id:1, name:"Zhang San", score:96.5 }
Equivalent to in java
package entity; public class User { private Integer id; private String name; private Double score; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getScore() { return score; } public void setScore(Double score) { this.score = score; } public User(Integer id, String name, Double score) { super(); this.id = id; this.name = name; this.score = score; } } User user = new User(1,"Zhang San",96.5);
Convert java objects to json format
User user = new User(1,"Zhang San",96.0); //Convert java objects to json format resp.setCharacterEncoding("utf-8"); JSONObject jsonObject = JSONObject.fromObject(user); resp.getWriter().write(jsonObject.toString());
2.3 cases
jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> <script type = "text/javascript" src = "js/jquery-3.0.0.min.js"></script> <script type="text/javascript"> /* $(function(){ alert(123) }) */ $(function(){ var btn = $("#btn"); btn.click(function(){ //alert("button clicked") $.ajax({ //Equivalent to < form action = "" > url:'testservlet', type:'get', data:'id=1', dataType:'text', success:function(data){ //alert(data) var text = $("#text"); text.before("<span>"+data+"</span><br>"); } }); }); }) </script> </head> <body> <input id = text type = "text"><br> <input id = "btn" type = "button" value = "Submit"><br> </body> </html>
Note 1: you can't submit a request with a form. Instead, you can submit it with jQuery dynamic binding time.
Note 2: servlet cannot jump directly to jsp, but can only return data// When alert(data) calls this comment statement, you can see the result, which is the reason.
servlet
package bysj01; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/testservlet") public class TestServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id"); try { Thread.sleep(30); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } String str = "Hello World"; resp.getWriter().write(str); // req.setAttribute("str", str); // req.getRequestDispatcher("test.jsp").forward(req, resp); } }
3. Traditional WEB data interaction VS AJAX data interaction
- The client requests differently
Traditional: browser sends synchronization request < form >, < a >
AJAX: asynchronous engine objects send asynchronous requests - The server responds differently
Traditional: respond to a complete jsp page (view)
AJAX: corresponding data required - Different client processing methods
Traditional: users need to wait for the server to complete the response and reload the whole page before they can carry out subsequent operations
AJAX: dynamically update the local content of the page without affecting other operations of the user
4. AJAX principle
5. Three level linkage cases
5.1 case description
It is divided into three parts: Province, city and district
When you click Province, the city and district will update automatically
5.2 code
location.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> <script type="text/javascript" src="js/jquery-3.0.0.min.js"></script> <script type="text/javascript"> $(function(){ //Modify Province $("#province").change(function(){ var id= $(this).val(); $.ajax({ url:"location", type:"post", data:"id="+id+"&type=province", dataType:"JSON", success:function(data){ console.log(data); var content = ""; var cities = data.cities; console.log(cities); for(var i=0;i<cities.length;i++){ content += "<option>"+cities[i]+"</option>"; } $("#city").html(content); content = ""; var areas = data.areas; console.log(areas); for(var i=0;i<areas.length;i++){ content += "<option>"+areas[i]+"</option>"; } $("#area").html(content); } }); }); //Modify City $("#city").change(function(){ var id = $(this).val(); $.ajax({ url:"location", type:"post", data:"id="+id+"&type=city", dataType:"JSON", success:function(data){ console.log(data) var content = ""; for(var i=0;i<data.length;i++){ content += "<option>"+data[i]+"</option>"; } $("#area").html(content); } }); }); }) </script> </head> <body> province:<select id="province"> <option value="Shaanxi Province">Shaanxi Province</option> <option value="Henan Province">Henan Province</option> <option value="Jiangsu Province">Jiangsu Province</option> </select> city:<select id="city"> <option value="Xi'an">Xi'an</option> <option value="Baoji City">Baoji City</option> <option value="Weinan City">Weinan City</option> </select> area:<select id="area"> <option value = "Yanta District">Yanta District</option> <option value = "Lianhu District">Lianhu District</option> <option value = "New urban area">New urban area</option> </select> </body> </html>
class:Location
package entity; import java.util.List; public class Location { private List<String> cities; private List<String> areas; public List<String> getCities() { return cities; } public void setCities(List<String> cities) { this.cities = cities; } public List<String> getAreas() { return areas; } public void setAreas(List<String> areas) { this.areas = areas; } }
servlet:LocationServlet
package servlet; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import entity.Location; @WebServlet("/location") public class LocationServlet extends HttpServlet { private static Map<String,List<String>> cityMap; private static Map<String,List<String>> provinceMap; static { cityMap = new HashMap<>(); List<String> areas = new ArrayList<>(); //Shaanxi Province //Xi'an areas.add("Yanta District"); areas.add("Lianhu District"); areas.add("New urban area"); cityMap.put("Xi'an", areas); //Baoji areas = new ArrayList<>(); areas.add("Chencang District"); areas.add("Weibin District"); areas.add("New urban area"); cityMap.put("Baoji City", areas); //Weinan areas = new ArrayList<>(); areas.add("Linwei "); areas.add("High tech Zone"); cityMap.put("Weinan City", areas); //Henan Province //Zhengzhou areas = new ArrayList<>(); areas.add("Zhengzhou A area"); areas.add("Zhengzhou B area"); cityMap.put("Zhengzhou City", areas); //Luoyang areas = new ArrayList<>(); areas.add("Luoyang A area"); areas.add("Luoyang B area"); cityMap.put("Luoyang City", areas); //Jiangsu Province //Nanjing areas = new ArrayList<>(); areas.add("Nanjing A area"); areas.add("Nanjing B area"); cityMap.put("Nanjing City", areas); //Suzhou areas = new ArrayList<>(); areas.add("Suzhou A area"); areas.add("Suzhou B area"); cityMap.put("Suzhou", areas); //Nantong areas = new ArrayList<>(); areas.add("Nantong A area"); areas.add("Nantong B area"); cityMap.put("Nantong City", areas); provinceMap=new HashMap<>(); List<String> cities = new ArrayList<>(); cities.add("Xi'an"); cities.add("Baoji City"); cities.add("Weinan City"); provinceMap.put("Shaanxi Province", cities); cities = new ArrayList<>(); cities.add("Zhengzhou City"); cities.add("Luoyang City"); cities.add("Kaifeng City"); provinceMap.put("Henan Province", cities); cities = new ArrayList<>(); cities.add("Nanjing City"); cities.add("Suzhou"); cities.add("Nantong City"); provinceMap.put("Jiangsu Province", cities); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String type = req.getParameter("type"); resp.setCharacterEncoding("utf-8"); String id = req.getParameter("id"); switch(type) { case "city": List<String> areas = cityMap.get(id); JSONArray jsonArray = JSONArray.fromObject(areas); resp.getWriter().write(jsonArray.toString()); break; case "province": List<String> cities = provinceMap.get(id); String city = cities.get(0); List<String> cityAreas = cityMap.get(city); Location location = new Location(); location.setCities(cities); location.setAreas(cityAreas); JSONObject jsonObject = JSONObject.fromObject(location); resp.getWriter().write(jsonObject.toString()); break; } } }