Ajax
The full name of AJAX is "Asynchronous JavaScript and XML". Using Ajax, we can update the page without refresh status, and realize asynchronous submission, which improves the user experience.
The essence of Ajax is to asynchronously send a request to the server by using a special object (XMLHttpRequest) provided by the browser. The server returns some data. The browser allows you to use these data to update the page. In the whole process, the page does not refresh and does not interrupt the user's operation
synchronization
At present, the interaction mode with the server is synchronous. When the client interacts with the server, the client can't do other operations. It can only wait for the response of the server and refresh the page
Asynchronous (asynchronous):
When the client is in normal operation, it can also interact with the server at the same time. The server responds to the client and updates the information to the part of the web page. The whole process of the page does not refresh
Create XMLHttpRequest object
• XMLHttpRequest object: send the request to the server and get the return result
• all modern browsers have built-in XMLHttpRequest objects. With a simple line of JavaScript code, we can create XMLHttpRequest objects.
xmlhttp=new XMLHttpRequest();
XMLHttpRequest
Method name | explain |
---|---|
open(method,URL,async) | Establish a connection with the server. The method parameter specifies the HTTP method of the request. Typical values are GET or post. The URL parameter specifies the address of the request. The async parameter specifies whether to use asynchronous requests. Its value is true or false |
send(content) | The send request content parameter specifies the parameters of the request |
setRequestHeader(header,value) | Set the header information of the request |
Ready status code | explain |
---|---|
0 | The XMLHttpRequest object did not complete initialization |
1 | The XMLHttpRequest object starts sending requests |
2 | The request sending of XMLHttpRequest object is completed |
3 | The XMLHttpRequest object started reading the response, but it hasn't finished yet |
4 | End of XMLHttpRequest object read response |
Status code | explain |
---|---|
200 | The server responded normally |
400 | The requested resource could not be found |
403 | No access |
404 | The accessed resource does not exist |
500 | Server internal error |
Get mode
xmlhttp.open("GET","testServlet?name="+userName,true);
xmlhttp.send(null);
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript"> function checkAccount(account) { //1. Create XMLHttprequest object var httpObj = new XMLHttpRequest(); //2. Use the XMLHTTPRequest object to send asynchronous requests to the server httpObj.open("get","${path}/ajax1",true);//Encapsulate request information httpObj.send("account="+account); //3. Get the data of the response from the XMLHttpRequest object //After the request is sent, the onreadystatechange event will be triggered httpObj.onreadystatechange=function (){ //The status code of status Http, 200 indicates that the response is normal if (httpObj.readyState==4&&httpObj.status==200){ //responseText get the response text content document.getElementById("msgid").innerHTML = httpObj.responseText; } } } </script> </head> <body> <input type="text" name="account" onblur="checkAccount(this.value)" ><span id="msgid"></span> <input type="password" name="password"> </body> </html>
servlet
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 java.io.IOException; import java.io.PrintWriter; @WebServlet(name = "ajax1", urlPatterns = "/ajax1") public class AjaxServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String account = req.getParameter("account"); resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = resp.getWriter(); if (account.equals("admin")){ out.print("Account already exists");//Respond to asynchronous requests }else{ out.print("√"); } } }
Post mode
xmlhttp.open("POST","testServlet",true);
For POST mode, you need to set the http request header yourself
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
Send data in POST mode
xmlhttp.send("name="+userName);
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript"> function checkAccount(account) { //1. Create XMLHTTPRequest object var httpObj = new XMLHttpRequest(); //2. Use the XMLHTTPRequest object to send asynchronous requests to the server httpObj.open("post","${path}/ajax1?account="+account,true);//Encapsulate request information //Set the request header. The internal submission format is the default format of the form httpObj.setRequestHeader("content-type","applicationCache/x-www-form-urlencoded") httpObj.send("account="+account+"&age=23");//Put the information in the request body //3. Fetch the data of the response from the XMLHTTPRequest object //After the request is sent, the onreadystatechange event will be triggered httpObj.onreadystatechange=function (){ if (httpObj.readyState==4&&httpObj.status==200){ document.getElementById("msgid").innerHTML = httpObj.responseText; } } } </script> </head> <body> <%-- enctype="multipart/form-data"submit document applicationCache/x-www-form-urlencoded Form default submission method key=value & key = value --%> <input type="text" name="account" onblur="checkAccount(this.value)" ><span id="msgid"></span> <input type="password" name="password"> </body> </html>
servlet
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 java.io.IOException; import java.io.PrintWriter; @WebServlet(name = "ajax1", urlPatterns = "/ajax1") public class AjaxServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String account = req.getParameter("account"); resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = resp.getWriter(); if (account.equals("admin")){ out.print("Account already exists"); }else{ out.print("√"); } } }
Json
jar package Download address:https://mvnrepository.com/artifact/com.google.code.gson/gson
JSON(JavaScript Object Notation) is a lightweight data exchange format (string of specific format)
In the key pair -- {Name: Jim} in the data
– data separated by commas List - > [{Name: Jim, age: 23}, {Name: Jim, age: 23}]
JSON key value pair is a way to save JS objects, and the writing method is similar to that of JS objects. The key name in the key / value pair combination is written in front and wrapped in double quotation marks "", separated by colon: and then followed by the value:
{"firstName": "John",age:23,...} \
[{"name":"value","sex":""},{"name":"value","sex":""},{"name":"value","sex":""}
When asynchronously exchanging data, java objects cannot be directly passed to js, so you need to first convert the java object into JSON format string, respond to the string to the client, and then the client can convert the JSON string into js object(
$.parseJSON(jsonstr) ).
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="${path}/js/jquery.1.8.3.min.js"></script> <script type="text/javascript"> function searchUser() { var user = document.getElementById("userId").value; var httpObj = new XMLHttpRequest(); httpObj.open("get","${path}/ajax2?user="+user,true); httpObj.send(); httpObj.onreadystatechange=function () { if (httpObj.readyState==4&&httpObj.status==200) //The string in json format is parsed into a javaScript object var jsobj = $.parseJSON(httpObj.responseText); document.getElementById("shouid").innerText = jsobj.name+":"+jsobj.age; } } </script> </head> <body> <input type="text" id="userId"> <input type="button" value="query" onclick="searchUser()"> <div id="shouid"> </div> </body> </html>
servlet
import com.ff.bean.User; import com.google.gson.Gson; 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 java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; @WebServlet(name = "ajax2", urlPatterns = "/ajax2") public class AjaxServlet2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String user = req.getParameter("user"); resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = resp.getWriter(); //Omit database query User user = new User(); user.setName(user); user.setAge(21); //First, convert the java object into a string in json format //String s = "{name:"+user1.getName()+",age:"+user1.getAge()+"}"; Gson gson = new Gson(); String s = gson.toJson(user1); System.out.println(s); out.print(s); } }
Asynchronous query of multiple data
import com.ff.bean.User; import com.google.gson.Gson; 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 java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; @WebServlet(name = "ajax2", urlPatterns = "/ajax2") public class AjaxServlet2 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String user = req.getParameter("user"); resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = resp.getWriter(); //Omit database query User user1 = new User(); user1.setName(user); user1.setAge(21); User user2 = new User(); user2.setName(user); user2.setAge(22); User user3 = new User(); user3.setName(user); user3.setAge(23); List<User> list = new ArrayList<>(); list.add(user1); list.add(user2); list.add(user3); Gson gson = new Gson(); String s = gson.toJson(list); System.out.println(s); out.print(s); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="${path}/js/jquery.1.8.3.min.js"></script> <script type="text/javascript"> function searchUser() { var user = document.getElementById("userId").value; var httpObj = new XMLHttpRequest(); httpObj.open("get", "${path}/ajax2?user=" + user, true); httpObj.send(); httpObj.onreadystatechange = function () { if (httpObj.readyState == 4 && httpObj.status == 200) { //The string in json format is parsed into a javaScript object var jsobjs = $.parseJSON(httpObj.responseText); var str = ""; for (i = 0; i < jsobjs.length; i++) { str += jsobjs[i].name + ":" + jsobjs[i].age + "<br/>"; } document.getElementById("shouid").innerHTML = str; } } } </script> </head> <body> <input type="text" id="userId"> <input type="button" value="query" οnclick="searchUser()"> <div id="shouid"> </div> </body> </html>
Jquery implements Ajax - $ Get() and $ post()
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script type="text/javascript" src="${path}/js/jquery.1.8.3.min.js"></script> <script type="text/javascript"> function checkAccount(account) { /* $.get("${path}/ajax1",{account:account},function (res) { $("#msgid").html(res); }) */ $.post("${path}/ajax1",{account:account},function (res) { $("#msgid").html(res); }) } </script> </head> <body> <input type="text" name="account" onblur="checkAccount(this.value)" ><span id="msgid"></span> <input type="password" name="password"> </body> </html>