Getting started with AJAX
AJAX introduction
- AJAX(Asynchronous JavaScript And XML): asynchronous JavaScript and XML. It is not a new technology in itself, but a combination of multiple technologies. Technology for quickly creating dynamic web pages.
- If you need to update the content of a normal web page, you must reload pages.
- AJAX can update web pages asynchronously by exchanging a little data between browser and server. That is to say, the partial content of the web page is updated without reloading the whole page.
- What is synchronization
- What is asynchronous
Native JavaScript implementation of AJAX
- Core object: XMLHttpRequest
Used to exchange data with the server in the background. You can update a part of a page without reloading the entire page.
- Open link: open(method,url,async)
method: the type of request GET or POST.
url: the path of the request resource.
async: true (asynchronous) or false (synchronous).
- Send request: send(String params)
params: the parameter of the request (special for POST).
- Processing response: onreadystatechange
readyState: 0-request uninitialized, 1-server connection established, 2-request received, 3-request processing, 4-request completed and response ready.
status: 200 - all responses are OK.
- Get response data form
responseText: get the response data in the form of string.
Response XML: get the response data in XML form.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User registration</title>
</head>
<body>
<form autocomplete="off">
//full name:<input type="text" id="username">
<span id="uSpan"></span>
<br>
//password:<input type="password" id="password">
<br>
<input type="submit" value="register">
</form>
</body>
<script>
document.getElementById("username").onblur = function() {
let xmlHttp = new XMLHttpRequest();
let username = document.getElementById("username").value;
xmlHttp.open("GET","userServlet?username="+username,true);
xmlHttp.send();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("uSpan").innerHTML = xmlHttp.responseText;
}
}
}
</script>
</html>
GET mode of jQuery to implement AJAX
- Core syntax: $. get(url,[data],[callback],[type]);
url: the resource path of the request.
data: the request parameter sent to the server. The format can be key=value or js object.
Callback: the callback function after the request is successful. We can write our logic code in the function.
Type: the expected return data type. The values can be xml, html, js, json, text, etc.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User registration</title>
</head>
<body>
<form autocomplete="off">
full name:<input type="text" id="username">
<span id="uSpan"></span>
<br>
password:<input type="password" id="password">
<br>
<input type="submit" value="register">
</form>
</body>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$("#username").blur(function () {
let username = $("#username").val();
$.get(
"userServlet",
"username="+ username,
function (data) {
$("#uSpan").html(data);
},
"text"
);
})
</script>
</html>
jQuery's POST implementation of AJAX
- Core syntax: $. post(url,[data],[callback],[type]);
url: the resource path of the request.
data: the request parameter sent to the server. The format can be key=value or js object.
Callback: the callback function after the request is successful. We can write our logic code in the function.
Type: the expected return data type. The values can be xml, html, js, json, text, etc
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User registration</title>
</head>
<body>
<form autocomplete="off">
full name:<input type="text" id="username">
<span id="uSpan"></span>
<br>
password:<input type="password" id="password">
<br>
<input type="submit" value="register">
</form>
</body>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$("#username").blur(function () {
let username = $("#username").val();
$.post(
"userServlet",
"username=" + username,
function (data) {
$("#uSpan").html(data);
},
"text"
);
});
</script>
</html>
The general way to implement AJAX in jQuery
- Core syntax: $. ajax({name:value,name:value ,… };
url: the resource path of the request.
async: asynchronous request or not, true yes, false no (the default is true).
Data: the data sent to the server can be in the form of key value pair or js object.
type: request method, POST or GET (GET by default).
dataType: the expected type of returned data. The values can be xml, html, js, json, text, etc.
success: the callback function that is called when the request is successful.
error: the callback function called when the request fails.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User registration</title>
</head>
<body>
<form autocomplete="off">
//full name:<input type="text" id="username">
<span id="uSpan"></span>
<br>
//password:<input type="password" id="password">
<br>
<input type="submit" value="register">
</form>
</body>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$("#username").blur(function () {
let username = $("#username").val();
$.ajax({
url:"userServletxxx",
async:true,
data:"username="+username,
type:"POST",
dataType:"text",
success:function (data) {
$("#uSpan").html(data);
},
error:function () {
alert("operation failed...");
}
});
});
</script>
</html>
AJAX quick start summary
- AJAX(Asynchronous JavaScript And XML): asynchronous JavaScript and XML.
- Through a small amount of data exchange between browser and server, web pages can be updated asynchronously. That is, without reloading the whole page, the part of the web page
Local update by content.
- Synchronous and asynchronous
Synchronization: the server cannot perform other operations during processing.
Asynchrony: the server can perform other operations during processing.
- GET mode implementation: $. get();
- POST mode implementation: $. post();
url: the resource path of the request.
data: the request parameter sent to the server. The format can be key=value or js object.
Callback: the callback function after the request is successful. We can write our logic code in the function.
Type: the expected return data type. The values can be xml, html, js, json, text, etc.
- Common way to implement: $. ajax();
url: the resource path of the request.
async: asynchronous request or not, true yes, false no (the default is true).
Data: the data sent to the server can be in the form of key value pair or js object.
type: request method, POST or GET (GET by default).
dataType: the expected type of returned data. The values can be xml, html, js, json, text, etc.
success: the callback function that is called when the request is successful.
error: the callback function called when the request fails.
JSON processing
JSON review
- JSON(JavaScript Object Notation): is a lightweight data exchange format.
- It is based on a subset of ECMAScript specification and uses a text format completely independent of programming language to store and represent data.
- The simple and clear hierarchy makes JSON an ideal data exchange language. It is easy for people to read and write, but also easy for computers to parse and generate, and effective
Improve network transmission efficiency.
- Create format
- common method
JSON conversion tool
- In addition to using JSON in JavaScript, we can also use JSON in JAVA. The conversion tools of JSON are some JAR toolkits packaged by JAVA.
- You can convert JAVA objects or collections to strings in JSON format, or you can convert strings in JSON format to JAVA objects.
- Jackson: open source and free JSON conversion tool. By default, Jackson is used for spring MVC conversion.
- Import the jar package.
- Create the core object.
- Call method to complete the conversion.
- Common classes
- Common methods of ObjectMapper
package com.itheima02;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashMap;
public class ObjectMapperTest {
private ObjectMapper mapper = new ObjectMapper();
@Test
public void test01() throws Exception {
User user = new User("Zhang San", 23);
String json = mapper.writeValueAsString(user);
System.out.println("json character string:" + json);
User user2 = mapper.readValue(json, User.class);
System.out.println("java Object:" + user2);
}
@Test
public void test02() throws Exception {
HashMap<String, String> map = new HashMap<>();
map.put("full name", "Zhang San");
map.put("Gender", "male");
String json = mapper.writeValueAsString(map);
System.out.println("json character string:" + json);
HashMap<String, String> map2 = mapper.readValue(json, HashMap.class);
System.out.println("java Object:" + map2);
}
@Test
public void test03() throws Exception {
HashMap<String, User> map = new HashMap<>();
map.put("Black horse class one", new User("Zhang San", 23));
map.put("Black horse class two", new User("Li Si", 24));
String json = mapper.writeValueAsString(map);
System.out.println("json character string:" + json);
HashMap<String, User> map2 = mapper.readValue(json, new TypeReference<HashMap<String, User>>() {
});
System.out.println("java Object:" + map2);
}
@Test
public void test04() throws Exception {
ArrayList<String> list = new ArrayList<>();
list.add("Zhang San");
list.add("Li Si");
String json = mapper.writeValueAsString(list);
System.out.println("json character string:" + json);
ArrayList<String> list2 = mapper.readValue(json,ArrayList.class);
System.out.println("java Object:" + list2);
}
@Test
public void test05 () throws Exception {
ArrayList<User> list = new ArrayList<>();
list.add(new User("Zhang San",23));
list.add(new User("Li Si",24));
String json = mapper.writeValueAsString(list);
System.out.println("json character string:" + json);
ArrayList<User> list2 = mapper.readValue(json,new TypeReference<ArrayList<User>>(){});
System.out.println("java Object:" + list2);
}
}
Summary of JSON processing
- Jackson: open source and free JSON conversion tool. By default, Jackson is used for spring MVC conversion.
- You can convert JAVA objects or collections to strings in JSON format, or you can convert strings in JSON format to JAVA objects.
- Common classes
- Common methods of ObjectMapper
Comprehensive case search Association
Case analysis and Implementation
- Bind the mouse click event to the user name input box.
- Get the entered user name data.
- Determine whether the user name is empty.
- If it is empty, the association prompt box will be hidden.
- If it is not empty, the AJAX request is sent and the data of the response is displayed in the association box.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User search</title>
<style type="text/css">
.content {
width: 643px;
margin: 100px auto;
text-align: center;
}
input[type='text'] {
width: 530px;
height: 40px;
font-size: 14px;
}
input[type='button'] {
width: 100px;
height: 46px;
background: #38f;
border: 0;
color: #fff;
font-size: 15px
}
.show {
position: absolute;
width: 535px;
height: 100px;
border: 1px solid #999;
border-top: 0;
display: none;
}
</style>
</head>
<body>
<form autocomplete="off">
<div class="content">
<img src="img/logo.jpg">
<br/><br/>
<input type="text" id="username">
<input type="button" value="Search for it">
<!--Data used to display Association-->
<div id="show" class="show"></div>
</div>
</form>
</body>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$("#username").mousedown(function () {
let username = $("#username").val();
if(username == null || username == "") {
$("#show").hide();
return;
}
$.ajax({
url:"userServlet",
data:{"username":username},
type:"POST",
dataType:"json",
success:function (data) {
let names = "";
for(let i = 0; i < data.length; i++) {
names += "<div>"+data[i].name+"</div>";
}
$("#show").html(names);
$("#show").show();
}
});
});
</script>
</html>
- Get the request parameters.
- Call the fuzzy query method of the business layer.
- Turn the returned data into JSON and respond to the client.
package com.itheima.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.bean.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
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.util.List;
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String username = req.getParameter("username");
UserService service = new UserServiceImpl();
List<User> users = service.selectLike(username);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(users);
resp.getWriter().write(json);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
}
Comprehensive case paging
Waterfall flow infinite load data paging
Case analysis
- How to make sure that the currently displayed data has been browsed?
Formula: (distance between the scroll bar and the bottom + distance between the scroll bar and the current window) > = height of the current document
Current document height: store 10 pieces of data, 100px.
Distance from scroll bar to bottom: 1px.
Height of current window: 80px.
Scroll bar up and down the distance: > = 19px.
- Prior knowledge
Case realization
- Define the send request tag.
- Defines the current page number and the number of bars displayed per page.
- Defines the distance from the bottom of the scroll bar.
- Set the page load event.
- Binds a scroll bar scroll event to the current window.
- Get the necessary information (height of the current window, the distance of scrolling up and down the scroll bar, height of the current document).
- Calculate whether the current display data has been browsed.
- Determine whether the request flag is true.
- Set the request flag to false. The request cannot be re initiated until the current asynchronous operation is completed.
- Query paging data based on the current page and the number of entries displayed per page.
- Current page number + 1.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Homepage</title>
<link rel="stylesheet" href="css/tt.css">
</head>
<body>
<div class="top">
<span class="top-left">downloadAPP</span>
<span class="top-left"> Beijing a sunny day</span>
<span class="top-right">More products</span>
</div>
<div class="container">
<div class="left">
<a>
<img src="img/logo.png"><br/>
</a>
<ul>
<li>
<a class="channel-item active" href="#">
<span>
recommend
</span>
</a>
</li>
<li><a class="channel-item" href="#">
<span>
video
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
hotspot
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
live broadcast
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
picture
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
entertainment
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
game
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
Sports
</span>
</a></li>
</ul>
</div>
<div class="center">
<ul class="news_list">
<li>
<div class="title-box">
<a href="#" class="link">
Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality11"
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality22"
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality33"
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality44"
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality55"
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality66"
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality77"
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality88"
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality99"
<hr>
</a>
</div>
</li>
<li>
<div class="title-box">
<a href="#" class="link">
Obama's rare involvement in the United States2020General election, warning Democratic Party candidates to be "based on reality1010"
<hr>
</a>
</div>
</li>
</ul>
<div class="loading" style="text-align: center; height: 80px">
<img src="img/loading2.gif" height="100%">
</div>
<div class="content">
<div class="pagination-holder clearfix">
<div id="light-pagination" class="pagination"></div>
</div>
</div>
<div id="no" style="text-align: center;color: red;font-size: 20px"></div>
</div>
</div>
</body>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
let send = true;
let start = 1;
let pageSize = 10;
let bottom = 50;
$(function () {
$(window).scroll(function () {
let windowHeight = $(window).height();
let scrollTop = $(window).scrollTop();
let docHeight = $(document).height();
if((bottom + scrollTop + windowHeight) >= docHeight) {
if(send == true) {
send = false;
queryByPage(start,pageSize);
start++;
}
}
});
});
function queryByPage(start,pageSize){
$(".loading").show();
$.ajax({
url:"newsServlet",
data:{"start":start,"pageSize":pageSize},
type:"POST",
dataType:"json",
success:function (data) {
if(data.length == 0) {
$(".loading").hide();
$("#no").html("I have a bottom line, too...");
return;
}
$(".loading").hide();
let titles = "";
for(let i = 0; i < data.length; i++) {
titles += "<li>\n" +
" <div class=\"title-box\">\n" +
" <a href=\"#\" class=\"link\">\n" +
data[i].title +
" <hr>\n" +
" </a>\n" +
" </div>\n" +
" </li>";
}
$(".news_list").append(titles);
send = true;
}
});
}
</script>
</html>
- Get the request parameters (current page, number of items displayed per page).
- According to the current Page number and the number of items displayed on each Page, call the method of the business layer to get the paging Page object.
- Turn the resulting data into json.
- Respond the data to the client.
package com.itheima.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.itheima.service.NewsService;
import com.itheima.service.impl.NewsServiceImpl;
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;
@WebServlet("/newsServlet")
public class NewsServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String start = req.getParameter("start");
String pageSize = req.getParameter("pageSize");
NewsService service = new NewsServiceImpl();
Page page = service.pageQuery(Integer.parseInt(start), Integer.parseInt(pageSize));
String json = new ObjectMapper().writeValueAsString(page);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resp.getWriter().write(json);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
}
Click button page
Analysis and implementation of cases
- The style file and js file of the paging plug-in are introduced.
- Defines the current page number and the number of bars displayed per page.
- Call the function that queries the data.
- Define the function to query paging data, and initiate AJAX asynchronous request.
- Set page number parameters (total and current pages) for the page button area.
- Bind the click event for the paging button to complete the query function of the previous page and the next page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Homepage</title>
<link rel="stylesheet" href="css/tt.css">
<link rel="stylesheet" href="css/simplePagination.css">
</head>
<body>
<div class="top">
<span class="top-left">downloadAPP</span>
<span class="top-left"> Beijing a sunny day</span>
<span class="top-right">More products</span>
</div>
<div class="container">
<div class="left">
<a>
<img src="img/logo.png"><br/>
</a>
<ul>
<li>
<a class="channel-item active" href="#">
<span>
recommend
</span>
</a>
</li>
<li><a class="channel-item" href="#">
<span>
video
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
hotspot
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
live broadcast
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
picture
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
entertainment
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
game
</span>
</a></li>
<li><a class="channel-item" href="#">
<span>
Sports
</span>
</a></li>
</ul>
</div>
<div class="center">
<ul class="news_list">
</ul>
<div class="content">
<div class="pagination-holder clearfix">
<div id="light-pagination" class="pagination"></div>
</div>
</div>
</div>
</div>
</body>
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/jquery.simplePagination.js"></script>
<script>
let start = 1;
let pageSize = 10;
queryByPage(start,pageSize);
function queryByPage(start,pageSize) {
$.ajax({
url:"newsServlet2",
data:{"start":start,"pageSize":pageSize},
type:"POST",
dataType:"json",
success:function (pageInfo) {
let titles = "";
for(let i = 0; i < pageInfo.list.length; i++) {
titles += "<li>\n" +
" <div class=\"title-box\">\n" +
" <a href=\"#\" class=\"link\">\n" +
pageInfo.list[i].title +
" <hr>\n" +
" </a>\n" +
" </div>\n" +
" </li>";
}
$(".news_list").html(titles);
$("#light-pagination").pagination({
pages:pageInfo.pages,
currentPage:pageInfo.pageNum
});
$("#light-pagination .page-link").click(function () {
let page = $(this).html();
if(page == "Prev") {
queryByPage(pageInfo.pageNum - 1,pageSize);
}else if (page == "Next") {
queryByPage(pageInfo.pageNum + 1,pageSize);
} else {
queryByPage(page,pageSize);
}
});
}
});
}
</script>
</html>
- Get the request parameters.
- According to the current Page number and the number of items displayed on each Page, call the method of the business layer to get the paging Page object.
- Encapsulates the PageInfo object.
- Turn the resulting data into json.
- Respond the data to the client.
package com.itheima.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.itheima.bean.News;
import com.itheima.service.NewsService;
import com.itheima.service.impl.NewsServiceImpl;
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.util.List;
@WebServlet("/newsServlet2")
public class NewsServlet2 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String start = req.getParameter("start");
String pageSize = req.getParameter("pageSize");
NewsService service = new NewsServiceImpl();
Page page = service.pageQuery(Integer.parseInt(start), Integer.parseInt(pageSize));
PageInfo<List<News>> info = new PageInfo<>(page);
String json = new ObjectMapper().writeValueAsString(info);
resp.getWriter().write(json);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
}