1. ajax overview
If the traditional web page needs to update the content, it must reload the whole web page. Whenever a user sends a request to the server, even if only a little local content needs to be updated, the server will refresh the whole page. The disadvantages of this approach are:
-
Performance will be reduced (a little content, refresh the whole page!)
-
The user's operation page will be interrupted (the whole page is refreshed)
1) What is Ajax
Ajax, namely "Asynchronous Javascript And XML", refers to a web page development technology for creating interactive web page applications. Ajax = Asynchronous Javascript And XML.
Ajax is a technology that allows the client to communicate asynchronously with the server when interacting with the server [without refreshing the whole browser]
2) The role of Ajax
Ajax can make web pages update asynchronously. This means that a part of a web page can be updated (local update) without reloading the whole web page.
3) Ajax benefits
- Reduce the burden on the server and obtain data as needed.
- No refresh to update the page, reducing the actual and psychological waiting time of users.
- Only some pages are updated to make effective use of bandwidth
- Mainstream browsers support Ajax
4) Asynchronous and synchronous
- How the browser accesses the server
- Synchronous access: the client must wait for the response from the server, and cannot perform other operations during the waiting process
- Asynchronous access: the client does not need to wait for the response of the service. During the waiting period, the browser can perform other operations
2. Implementation of ajax in JS mode (understand)
ajax of JS: first appeared. Use an XmlHttpRequest object. It is specially used for sending ajax requests and receiving responses
Send a request using ajax, receive a response using ajax, and refresh the page using JS.
-
Disadvantages:
- If you use AJAX technology of JS, you need to write a lot of complex code in order to realize simple functions.
- JS AJAX code, browser compatibility is poor.
The front-end JS code can be copied
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>new jsp</title> <script> function run() { //1. Create core objects var xmlhttp; //2. Judge browser type if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //3. Establish connection /** * Three parameters: * 1.Request method: get post * 2.The path to the requested resource * 3.Asynchronous yes or no */ xmlhttp.open("GET","/login?username=tom",true); //4. Send request xmlhttp.send(); //5. Get response results /** * When do I get the response data? * Get after the server responds successfully */ //Listen for readyState state changes xmlhttp.onreadystatechange=function() { //readyState==4, the response is ready, and the 200 access is successful if (xmlhttp.readyState==4 && xmlhttp.status==200) { //Get response data var text = xmlhttp.responseText; alert(text); } } } </script> </head> <body> <input type="button" value="Send asynchronous request" onclick="run()"><br> Local refresh <input type="text"> </body> </html>
Backend Servlet
@WebServlet("/login") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. Get request data String username = req.getParameter("username"); //Print username System.out.println(username); resp.getWriter().write(username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
3. ajax of jQuery framework
3.1 introduction to ajax of jQuery framework
jquery is an excellent js framework, which naturally encapsulates the native ajax of js. The operation method of the encapsulated ajax is simpler and more powerful
There are several jquery methods related to ajax operation, but three are often used in development: POST GET AJAX
3.2 GET request method
Load information via remote HTTP GET request. This is a simple GET request function. For complex Ajax parameter settings, please use $ ajax
Get request mode syntax
$.get(url,data,callback,type)
- Parameter 1: url request path
- Parameter 2: data carried in data request
Format: key=value or {username = 'baby', pwd:666} - Parameter 3: callback function after successful callback response
- Parameter 4: data type of type response text html xml json
Code example
//Send asynchronous request in JQuery get mode function run2() { //1. Parameter 1 url var url = "/login"; //2. parameter 2 data var data = {username:"jack"}; //3. Send get request $.get(url,data,function (param) { //Content body of data response alert("Response successful! Response data: " + param); },"text"); }
3.3 POST request mode
Load information via remote HTTP POST request. This is a simple POST request function. For complex Ajax parameter settings, please use $ ajax
Post request mode syntax
$.post(url,data,callback,type)
The four parameters are the same as the get method, but the difference is the request method
Code example
//Send asynchronous request in JQuery post mode function run3() { //1. Parameter 1 url var url = "/login"; //2. Parameter 2 data var data = {username:"lucy"}; //3. Send get request $.post(url,data,function (param) { //Content body of data response alert("Response successful! Response data: " + param); },"text"); }
3.4 Ajax request mode
The $. ajax() method can set the underlying parameters in more detail. This method is usually used for requests that cannot be completed by other methods.
ajax request mode syntax:
- Method 1: jQuery ajax({[settings]})
- Mode 2: $ ajax({})
settings is a js literal object in the form of key value pair {name:value,name:value}. The common name attribute names are as follows:
Code example
//Send request in Ajax mode function run4() { $.ajax({ url:"/login", async:true, //Asynchronous data:{username:"tom"}, type:"POST", //Request mode dataType:"text", //The data type of the returned data success:function (param) { alert("Response successful!! " + param) }, error:function () { alert("Response failed!!") } }); }
4. Case: check whether the user name has been registered
Requirement: the user enters the user name, and after the mouse is removed, the user will judge the user name and prompt whether the user name is available
Steps:
- Prepare the Servlet, verify the user name, and return the result (available or not)
- For the page input box, bind the mouse removal event
- Make an asynchronous request and get the response result
- Add HTML code dynamically according to the results
Background Servlet
@WebServlet("/checkName") public class CheckNameServelt extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=utf-8"); //Get name String username = req.getParameter("username"); //Encapsulate data HashMap<String,Object> map = new HashMap<>(); //Determine whether the user exists if("tom".equals(username)){ map.put("flag",true); map.put("msg","User name already occupied!"); String data = JSON.toJSONString(map); resp.getWriter().print(data); }else{ //User name is not used map.put("flag",false); map.put("msg","User name can be used!"); String data = JSON.toJSONString(map); resp.getWriter().print(data); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
Foreground JSP
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>new jsp</title> <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script> $(function() { $("#username").blur(function () { //Get user name var name = $(this).val(); //Judge that the user name is not empty if(name != null && name != ""){ $.ajax({ url:"/checkName", type:"GET", data:{username:name}, dataType:"json", success:function (data) { if(data.flag){ //Set span content body $("#spanMsg").html("<font color='red'>" + data.msg+ "</font>"); }else if(!data.flag){ $("#spanMsg").html("<font color='green'>"+ data.msg + "</font>"); } }, error:function () { alert("Request processing failed!") } }); } }) }); </script> </head> <body> <form action="#" method="post"> user name: <input type="text" id="username" name="username" placeholder="enter one user name"> <span id="spanMsg" style="color:red"></span><br> password: <input type="text" name="password" placeholder="Please input a password"><br> </form> </body> </html>
Case source code download: Ajax - sample code