Ajax class notes

Keywords: JSON JQuery xml Java

Ajax class notes

  • jQuery simplifies js, mainly dom operation

    • Find it (selector)
    • Do it (dom operation method)
  • selector

    • Basic selector
      • $("div")
      • $("#div")
      • $(".cls")
    • Level selector
      • $("div span"): a selector connected with spaces to find descendants
      • $("div > span"): use the selector of > connection to find child elements
    • attribute selectors
      • $("a[class]"): a element with a class attribute
      • $("a[class='btn ']"): a element whose class attribute value is BTN
      • $("a [] []"): composite property selector
    • Basic filter selector:
      • : first find the first
      • : last
      • : not(selector): do not exclude selector results
      • : even find even index
      • : odff for index odd
      • : eq(n) find the index equal to n
      • : gt(n) find the index greater than n
      • : lt(n) find the index less than n
    • Form property selector
      • : enabled find available form items
      • : disabled find unavailable form item
      • : checked to find the selected radio or checkbox
      • : selected find the selected dropdown option option
  • Method of dom operation

    • Operation label body
      • html(): get the content in the label body. If there is a parameter to set the label body content (overriding setting, setting html code is valid)
      • text(): gets the text of the label body. If there is a parameter, it means to set the label body text (overriding setting, setting html code does not take effect)
    • Value of action form item:
      • val() has no parameter to get the value of the form item. Parameter means setting the value of form item
    • Operation properties
      • prop(name): get attribute value
      • prop(name,value): set property value
      • attr(name): get attribute value
      • attr(name, value): set attribute value
      • Note: if you want to operate on the selected and checked properties, you must use the prop method
      • For operations of other attributes, attr() is preferred. If not, prop is used
    • Operation style
      • css(name): get style value
      • css(name,value): set the style
      • addClass(className): add a class name
      • removeClass(className): delete class name
      • toggleClass(className): toggles the class name. Delete if there is one, and add if there is none
    • Operation label:
      • $("< li > < / Li >") create a Li label
      • parent.append(child), child.appendTo(parent): insert the child into the parent, and finally
      • parent.prepend(chilc),child.prependTo(parent): insert the child into the front of the parent
      • remove(): delete the label itself to include everything
      • empty(): empty the contents of the tag, but the tag itself remains
  • event:

    • The difference between js event and js event:
      • Event name without on
      • Events are methods
      • Response behavior as an argument to a method
    • Common events:
      • click(function(){})
      • dblclick()
      • submit()
      • change()
      • focus(), blur()
      • Keyboard 3, mouse 5
    • There is a special event: page loading is complete
    $(function(){
        alert("jQuery Page loading completion shorthand form of");
    })
    $(document).ready(function(){
        alert("jQuery Complete form of page loading of");
    });
    

1, jQuery

Event binding and unbinding [learn]

target

  • Master the way to unbind events

explain

API
  • on("event name", function() {}), another way of event binding
  • off("event name"), unbind event
Example
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Event binding and unbinding</title>
</head>
<body>

<input type="button" value="Click pop up" id="btn">

<script src="js/jquery-3.4.1.min.js"></script>
<script>
    //Bind the click event to the btn button, and click the pop-up window
    $("#btn").on("click", function(){
        alert("Mouse click");
    });

    //Click event is unbound, so click btn button, no pop-up window
    $("#btn").off("click");
</script>
</body>
</html>

Summary

Loop traversal

target

  • Grasp the loop traversal of js
  • Understanding the loop traversal of jQuery

step

  1. js's for i loop and for of cycle
  2. Two loops of jQuery

explain

js's for i loop and for of cycle [mastery]
let items = $("li");

for(let i=0; i<items.length; i++){
    console.log(items[i]);
}

for(let element of items){
    console.log(element);
}
Two loops of jQuery [understanding]
let items = $("li");

items.each(function(index, element){
    console.log("Indexes:" + index + ", Element:" + element);
});

$.each(items, function(index,element){
    console.log("Indexes:" + index + ", Element:" + element);
});

Summary

2, JSON

The function of xml: transfer data, configuration file, store data

xml defined syntax:

xml parsing:

The problem of xml: too much syntax

js provides a data format: json, instead of xml

target

  • Understand the role of json
  • Ability to define and parse json

explain

1. What is json
  • json: JavaScript Object Notation, js object notation. Is a lightweight data format that can replace XML.
  • Data is stored and represented in a completely language independent text format.
  • 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 machines to parse and generate, and effectively improve the efficiency of network transmission.
2. json syntax
  • Defined syntax:

    • Object form: {"key":value, "key":value,...}
      • Format similar to js object:{ key:value, key:value , ...}
      • key in json format, all strings
    • Array form: [value1, Value2, value3,...] let arr = ["a", "B", "C"]
    • Mixing form: any mixing of the above two types
  • Parsing syntax:

    • Take the data from the array and use the index: json array object [index]
    • Take the data from the object and use the json object. key
  • Conversion of JSON object and string

    method parameter Return value explain
    JSON.stringify(json) json object / json array character string Convert json object to string type
    JSON.parse(string) character string json object / json array Parsing strings into json objects / arrays
3. json definition and parsing exercise
  • Object form

    //Defining a json object is simpler than xml format
    let obj = {"name":"Sanfeng", "age":100};
    
    //Parse the json object and get the value of name
    let v = obj.name;
    alert(v);
    
  • Mixed form

    //Define an array in which each element is a json object
    let wudang = [
        {"name":"Sanfeng", "age":100},
        {"name":"Cuishan mountain", "age":40},
        {"name":"Green Book", "age":20}
    ];
    //Parse, get the name of the third element
    let v = wudang[2].name;
    alert(v);
    

Summary

3, Introduction to Ajax

Note: the service needs to be started before all Ajax features in the document can be demonstrated. Refer to materials / services for startup mode

target

  • Understand the concept of Ajax
  • Understanding the effects of synchronization and asynchrony

explain

1. What is Ajax

  • Ajax: Asynchronous JavaScript and XML, asynchronous JS and XML.
    • Javascript: Ajax technology is provided by JavaScript
    • XML: the data format used by server and client is XML, but it has been replaced by JSON.
  • The role of Ajax:
    • Local refresh technology: refresh only a part of the page, not the whole page. Fast refresh speed, good user experience
    • Asynchronous loading technology: after the request is sent, you can continue to do other things without waiting for the result.

2. Synchronous and asynchronous [understanding]

  • Synchronous loading: after the request is sent, it is in the "feign dead" state while waiting for the response of the server
  • Asynchronous loading: after the request is sent and before the response comes back, you can still do other operations without "feigning death"

3. Ajax usage scenarios

  • If you need to complete some functions without refreshing the page, you need to use Ajax to achieve this function.
  • Origin: Microsoft's IE, but promoted by chrome: Chrome's gmail mailbox uses its own Ajax technology

Summary

  • Understand the concept of Ajax
    • Technology of asynchronous loading and local refresh
    • If you implement a function that requires that the page must not be refreshed, you need to use Ajax technology; otherwise, it depends on requirements, design, company or client requirements
  • Understanding the effects of synchronization and asynchrony
    • Synchronization: after a request is sent, it will "feign death" while waiting for a response
    • Asynchronous: after the request is sent, it will not "feign death" until the response comes back. Other operations can be performed

4, Ajax of js [learn]

target

  • Using js to achieve Ajax effect
  • Understand the effect of asynchronous loading
  • Understand the effect of local refresh

analysis

  1. Create an Ajax engine object
  2. Bind events to Ajax engine objects and listen for state changes.
    • If you hear that the Ajax engine has received a response, you can ask the Ajax engine for the response result
  3. Set the requested information for the Ajax engine object
  4. Let Ajax engine objects send requests

realization

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js Of Ajax</title>
</head>
<body>
<input type="button" value="js Of Ajax" onclick="jsAjax()">

<div id="resultDiv">
    //Show the final response here
</div>

<script>
    function jsAjax() {
        //1. Create Ajax engine objects
        let xmlhttp = new XMLHttpRequest();
        //2. Binding events to Ajax engine objects
        xmlhttp.onreadystatechange = function(){
            //If the response is normal
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                //Get the result of the server response and display it in resultDiv on the page
                let result = xmlhttp.responseText;
                document.querySelector("#resultDiv").innerHTML = result;
            }
        };
        //3. Set whether the request information request mode request path is asynchronous
        xmlhttp.open("post", "http://localhost:18888/base", true);
        //4. Send request
        xmlhttp.send();
    }
</script>
</body>
</html>

The Ajax problem of js:

  1. Too many duplicate codes. Different functions are just the processing of request information and response results is different, the others are exactly the same
  2. There is a browser compatibility issue.

Summary

5, Ajax of jQuery

target

  • Ability to use $. post() and $. get() methods
  • Ability to use $. ajax() method

explain

1. $.get() and $. post()

1.1 grammar
  • It's all asynchronous
  • $. get(url, data, callback, type): GET request

  • $. post(url, data, callback, type): POST mode request

  • Parameters:

    • url: the address of the request. must

    • data: submitted form parameters. No, there are two formats:

      • name=value&name=value&...
      • {name:value, name:value, ...}
    • Callback: a callback function. It is not required. It is an anonymous function. It says: processing response results

      function(result){
          //Result: the result of the server response
      }
      
    • Type: the result type of the server response, not required. text, json

1.2 example
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery Of Ajax</title>
</head>
<body>
<input type="button" value="jQuery Of Ajax: get()" id="getBtn">
<input type="button" value="jQuery Of Ajax: post()" id="postBtn">


<div id="resultDiv">
    Show the final response here
</div>

<script src="js/jquery-3.4.1.min.js"></script>
<script>
    $("#getBtn").click(function () {
        let params = "name=Zhang San&age=30";
        $.get("http://localhost:18888/base", params, function(result){
            $("#resultDiv").html(result);
        },"text");
    });

    $("#postBtn").click(function () {
        let params = "name=Li Si&age=40";
        $.post("http://localhost:18888/base",params, function(result){
            $("#resultDiv").html(result);
        },"text");
    });
</script>
</body>
</html>

2. $.ajax()

2.1 syntax:
  • $.ajax({key:value, key:value ,...}). Each key is a configuration item. Common configuration items include:
    • url: the address of the request. must
    • data: the parameter of the form to be submitted. There are two formats:
      • name=value&name=value&...
      • {key:value, key:value,...}
    • type: request mode. GET/POST is commonly used. Put and delete will be used in the future
    • dataType: the data type / format of the server response. Commonly used data types are text and JSON
    • success: callback function, used to process the result
    • async: asynchronous or not. The default value is true
2.2 example:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery Of Ajax method</title>
</head>
<body>

<input type="button" value="jQuery Of Ajax: ajax()" id="ajaxBtn">
<div id="resultDiv">
    //Show the final response here
</div>

<script src="js/jquery-3.4.1.min.js"></script>
<script>
    $("#ajaxBtn").click(function () {
        $.ajax({
            url:"http://localhost:18888/base",
            data:"name=Xiao Wang&age=18",
            type:"get",
            dataType:"text",
            success:function(result){
                $("#resultDiv").html(result);
            },
            async:true
        });
    });
</script>
</body>
</html>

Summary

  • $. get(url, data, callback, teyp): send GET Ajax request

  • $. post(url, data, callback, type): send POST Ajax request

    • Parameter Description:

      • url: request address

      • data: the form parameters submitted when sending the request. There are two formats

        • String: name = value & name = value &
        • json object:{ name:value, name:value , ....}
      • Callback: a callback function that processes the result of a response

        function(result){}
        
      • type: data format of server response, common text, json

  • $.ajax({key:value,key:value ,...}): closer to the bottom, so the configuration is more flexible, but it is also more cumbersome to use

    • Parameter Description: each key:value It is a configuration item. Common configuration items include

      • url: request address

      • data: submit form parameters in two formats:

        • name=value&name=value&.... For example: username = Tom & password = 1234
        • { name:value, name:value ,...} . For example: {username:"tom", password:"1234"}
      • type: request method, commonly used get, post. Get by default

      • dataType: the format of the result data returned by the server, common text, json

      • success: callback function to process the result returned by the server

        function(result){
            //Result: data result returned by the server
        }
        
      • async: asynchronous or not. true is asynchronous, false is not asynchronous

6, Exercise: asynchronous search feature

target

  • Realize asynchronous search function

[failed to transfer the pictures in the external link. The source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-p1tj4xf5-1593307584967)(img \ asynchronous search function effect demonstration. gif))

analysis

  1. Result list, which should be hidden by default
  2. When entering in the search box:
    • If the input is empty: clear and hide the result list
    • If the input is not empty:
      • Send asynchronous request to the server, pass the input content to the server, and get the search results
      • If the search results are empty: empty and hide the results list
      • If the search result is not empty:
        • Clear and display the result list first
        • Loop search results into the results list

realization

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <style type="text/css">
        .content{
            width:643px;
            margin:50px 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
        }
        .result{
            /*position: absolute;*/
            width: 535px;
            border: 1px solid #999;
            border-top: 0;

            display: none;
        }
        .result div:hover{
            background-color: #ccc;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="content">
    <img alt="" src="img/logo.png"><br/><br/>
    <input type="text" name="word" id="searchWord">
    <input type="button" value="Search for it">
    <div class="result">
		<div>Zhang San</div>
		<div>Zhang Sanfeng</div>
	</div>
</div>
<script type="text/javascript" src="./js/jquery-3.3.1.js"></script>
<script type="text/javascript">
    $("#searchWord").keyup(function () {
        //If the search box is empty: clear the result list and hide it
        if (this.value === ""){
            $(".result").empty().hide();
            return;
        }

        //Send asynchronous request to the server, and pass the content in the search box to the server to get the search results
        $.post("http://localhost:18888/search", "name="+this.value, function(result){
            if (result == null || result.length === 0) {
	            //If the search result is empty: clear the result list and hide it
                $(".result").empty().hide();
            }else{
                //If the search result is not empty: clear the result list and display
                $(".result").empty().show();
                //Loop search results into the results list
                for (let user of result) {
                    $("<div></div>").html(user.name).appendTo(".result");
                }
            }
        }, "json");
    });
</script>
</body>
</html>

Summary

Content sorting in the morning

  • jQuery's
    • Event binding and unbinding [learn]
    • Loop traversal
      • Two cycles of js [Master]
      • Two loops of jQuery [understanding]
  • JSON [Master]
    • Definition of json
      • Object form: {"key":value, "key":value,....}
      • Array form: [value1, value2, value3,...]
      • Mixed form: mixed use of the above two forms
    • Analysis of json
      • Get the value of the specified key from the object: json object. Key
      • Get the value of the specified index from the array: json array [index]
    • Transformation of json
      • To convert a json object to a string: JSON.stringify(jsonObj)
      • json format string conversion concerns json objects: JSON.parse(string)
  • Ajax
    • Synchronous and asynchronous
      • Synchronization: will "feign death" while waiting for response
      • Asynchrony: No "feign death" while waiting for response
    • Ajax of jQuery: [Master]
      • $.get(url, data, callback, type)
      • $.post(url, data, callback, type)
      • $.ajax({key:value, key:value,...})
        • url: request address
        • data: submitted form parameters
        • type: request method get, post
        • dataType: data format returned by the server
        • success: callback function
        • async: asynchronous or not
  • 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.

7, Comprehensive case search Association

  • Writing association words

  • page

    1. Bind the mouse click event to the user name input box.

    2. Get the entered user name data.

    3. Determine whether the user name is empty.

    4. If it is empty, the association prompt box will be hidden.

    5. If it is not empty, the AJAX request is sent and the data of the response is displayed in the association box.

  • Control layer

  1. Get the request parameters.

  2. Call the fuzzy query method of the business layer.

  3. 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 {
            //Set the encoding of requests and responses
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");
    
            //1. Get request parameters
            String username = req.getParameter("username");
    
            //2. Call the fuzzy query method of business layer to get data
            UserService service = new UserServiceImpl();
            List<User> users = service.selectLike(username);
    
            //3. Convert the data to JSON and respond to the client
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(users);
           // String json = new ObjectMapper().writeValueAsString(users);
    
            //Respond the json string to the front-end callback function
            resp.getWriter().write(json);
        }
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req,resp);
        }
    }
    
    <!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-1.8.3.min.js"></script>
    <script>
    
        /*//practice
        $("#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();
                }
            });
        });
        */
    
        //1. Bind mouse click event for user name input box
        $("#username").mousedown(function () {
            //2. Get the entered user name
            let username = $("#username").val();
    
            //3. Judge whether the user name is empty
            if(username == null || username == "") {
                //4. If it is empty, hide the association box
                $("#show").hide();
                return;
            }
    
            //5. If it is not empty, send AJAX request. And display the data to the Lenovo box
            $.ajax({
                //Requested resource path
                url:"userServlet",
                //Request parameters
                data:{"username":username},
                //Request method
                type:"POST",
                //Response data form
                dataType:"json",
                //Callback function after successful request
                success:function (data) {//data is directly a js object, because jquery has converted the json string into a js object
                    //Display the returned data to show's div
                    let names = "";
                    for(let i = 0; i < data.length; i++) {
                        names += "<div>"+data[i].name+"</div>";
                    }
                    $("#show").html(names);
                    $("#show").show();
                }
            });
        });
    </script>
    </html>
    

8, Comprehensive case waterfall Pagination

1. 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

function explain
$(function(){}) Page load event
$(window) Get current window object
scroll() Mouse scrolling events
$(window).height() Current window height
$(window).scrollTop() How far up and down the scroll bar
$(document).height() Height of the current document

2. Case realization

  • page

    1. Define the send request flag.

    \2. Define the current page number and the number of bars displayed per page.

    \3. Define the distance from the bottom of the scroll bar.

    \4. Set the page load event.

    \5. Bind scrollbar scrolling events to the current window.

    \6. Get necessary information (the height of the current window, the distance of scrolling up and down the scroll bar, and the height of the current document).

    \7. Calculate whether the current display data has been browsed.

    \8. Judge whether the request tag is true.

    \9. Set the request flag to false. The request cannot be re initiated until the current asynchronous operation is completed.

    \10. Request to query the paging data according to the current page and the number of entries displayed on each page. (the query data is appended to the ul tag)

    \11. Current page + 1

  • The server

    1. Get the request parameters (current page, number of items displayed per page).

    2. 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.

    1. Turn the resulting data into json.

    2. Respond the data to the client.

      <!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">download APP</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 rarely intervenes in the US 2020 election, warning Democratic Party candidates to "based on reality 11"
                              <hr>
                          </a>
                      </div>
                  </li>
                  <li>
                      <div class="title-box">
                          <a href="#" class="link">
                              Obama rarely intervenes in the US 2020 election, warning Democratic Party candidates to be "reality based 22"
                              <hr>
                          </a>
                      </div>
                  </li>
                  <li>
                      <div class="title-box">
                          <a href="#" class="link">
                              Obama rarely intervenes in the US 2020 election, warning Democratic Party candidates to "based on reality 33"
                              <hr>
                          </a>
                      </div>
                  </li>
                  <li>
                      <div class="title-box">
                          <a href="#" class="link">
                              Obama rarely intervenes in the US 2020 election, warning Democratic Party candidates to "based on reality 44"
                              <hr>
                          </a>
                      </div>
                  </li>
                  <li>
                      <div class="title-box">
                          <a href="#" class="link">
                              Obama rarely intervenes in the US 2020 election, warning Democratic Party candidates to be "reality based 55"
                              <hr>
                          </a>
                      </div>
                  </li>
                  <li>
                      <div class="title-box">
                          <a href="#" class="link">
                              Obama rarely intervenes in the US 2020 election, warning Democratic Party candidates to "based on reality 66"
                              <hr>
                          </a>
                      </div>
                  </li>
                  <li>
                      <div class="title-box">
                          <a href="#" class="link">
                              Obama rarely intervenes in the US 2020 election, warning Democratic Party candidates to "based on reality 77"
                              <hr>
                          </a>
                      </div>
                  </li>
                  <li>
                      <div class="title-box">
                          <a href="#" class="link">
                              Obama rarely intervenes in the US 2020 election, warning Democratic Party candidates to "based on reality 88"
                              <hr>
                          </a>
                      </div>
                  </li>
                  <li>
                      <div class="title-box">
                          <a href="#" class="link">
                              Obama rarely intervenes in the US 2020 election, warning Democratic Party candidates to "based on reality 99"
                              <hr>
                          </a>
                      </div>
                  </li>
                  <li>
                      <div class="title-box">
                          <a href="#" class="link">
                              Obama rarely intervenes in the US 2020 election, warning Democratic Party candidates to "based on reality 1010"
                              <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-1.8.3.min.js"></script>
      <script>
          //1. Define send request flag
          let send = true;
      
          //2. Define the current page number and the number of bars displayed per page
          let start = 1;
          let pageSize = 10;
      
          //3. Define the distance between the scroll bar and the bottom
          let bottom = 1;//The larger the number, the earlier the load time
      
          //4. Set page loading event
          $(function () {
              //5. Bind scrollbar scrolling events to the current window
              $(window).scroll(function () {
                  //6. Obtain necessary information to calculate whether the current display data has been browsed
                  //Height of the current window
                  let windowHeight = $(window).height();
      
                  //Scroll bar scroll distance from top to bottom
                  let scrollTop = $(window).scrollTop();
      
                  //Height of the current document
                  let docHeight = $(document).height();
      
                  //7. Calculate whether the current display data has been browsed and send a request to load new data at this height
                  //When the distance from the bottom of the scroll bar + the distance from the current scroll bar + the height of the current window > = the height of the current document
                  if((bottom + scrollTop + windowHeight) >= docHeight) {
                      //8. Judge whether the request flag is true
                      if(send == true) {
                          //9. Set the request flag to false. The request cannot be re initiated until the current asynchronous operation is completed.
                          send = false;
                          //10. Request to query paging data according to the current page and the number of entries displayed on each page
                          queryByPage(start,pageSize);
                          //11. Current page + 1
                          start++;
                      }
                  }
              });
          });
      
          //Define functions to query paging data
          function queryByPage(start,pageSize){
              //Loading dynamic diagram display
              $(".loading").show();
              //Launch AJAX request
              $.ajax({
                  //Requested resource path
                  url:"newsServlet",
                  //Requested parameters
                  data:{"start":start,"pageSize":pageSize},
                  //How to request
                  type:"POST",
                  //Response data form
                  dataType:"json",
                  //Callback function after successful request
                  success:function (data) {
                      if(data.length == 0) {
                          $(".loading").hide();
                          $("#no").html("I have a bottom line, too...");
                          return;
                      }
                      //Load dynamic hide
                      $(".loading").hide();
                      //Display data
                      let titles = "";
                      for(let i = 0; i < data.length; i++) {
                              titles += `<li>
                                            <div class="title-box">
                                                <a href="#" class="link">
                                                ${data[i].title}  <!--String splicing-->
                                                <hr>
                                                </a>
                                            </div>
                                         </li>`
                      }
      
                      //Show to page
                      $(".news_list").append(titles);//Append the existing data
                      //Set request flag to true
                      send = true;
                  }
              });
          }
      
      </script>
      </html>
      

      The server

      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 {
              //Set the encoding of requests and responses
              req.setCharacterEncoding("UTF-8");
              resp.setContentType("text/html;charset=UTF-8");
      
              //1. Get request parameters
              String start = req.getParameter("start");
              String pageSize = req.getParameter("pageSize");
      
              //2. Call the query method of the business layer according to the current Page number and the number of items displayed on each Page to get the paged Page object
              NewsService service = new NewsServiceImpl();
              Page page = service.pageQuery(Integer.parseInt(start), Integer.parseInt(pageSize));
      
              //3. Convert the data to JSON
              String json = new ObjectMapper().writeValueAsString(page);
      
              try {
                  Thread.sleep(1000);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
      
              //4. Respond the data to the client
              resp.getWriter().write(json);
          }
      
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              doPost(req,resp);
          }
      }
      
      

3. Click the button to page

  • page

    1. The style file and js file of the paging plug-in are introduced.

    2. Defines the current page number and the number of bars displayed per page.

    3. Call the function that queries the data.

    4. Define the function to query paging data, and initiate AJAX asynchronous request.

    5. Set page number parameters (total and current pages) for the page button area.

    6. Bind the click event for the paging button to complete the query function of the previous page and the next page.

  • The server

  1. Get the request parameters.

  2. 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.

  3. Encapsulates the PageInfo object.

  4. Turn the resulting data into json.

  5. Respond the data to the client.

<!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">download APP</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>

            <!--Basic structure (elements for page numbers)-->
        <div class="content">
            <div class="pagination-holder clearfix">
                <div id="light-pagination" class="pagination"></div>
            </div>
        </div>

    </div>
</div>
</body>         <!--forerunner jquery,Import the paging plug-in again because of dependency-->
<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/jquery.simplePagination.js"></script>
<script>
    //1. Define the current page number and the number of bars displayed per page
    let start = 1;
    let pageSize = 10;

    //2. Call the method to query data
    queryByPage(start,pageSize);

    //3. Define the function to query the paging data, initiate AJAX asynchronous request, and display the data to the page
    function queryByPage(start,pageSize) {
        $.ajax({
            //Requested resource path
            url:"newsServlet2",
            //Requested parameters
            data:{"start":start,"pageSize":pageSize},
            //How to request
            type:"POST",
            //Response data form
            dataType:"json",
            //Callback function after successful request
            success:function (pageInfo) {
                //Show data to page
                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);//Overlay each overlay to form new content

                //4. Set page number parameters (total pages and current pages) for page button area
                $("#light-pagination").pagination({
                    pages:pageInfo.pages,
                    currentPage:pageInfo.pageNum
                });

                //5. Bind the click event for the paging button to complete the query function of the previous page and the next page
                $("#light-pagination .page-link").click(function () {
                    //Get the text content of the click button
                    let page = $(this).html();
                    //If Prev is clicked, call the query method to query the data on the previous page of the current page
                    if(page == "Prev") {
                        queryByPage(pageInfo.pageNum - 1,pageSize);
                    }else if (page == "Next") {
                        //If you click Next, call the query method to query the data on the Next page of the current page
                        queryByPage(pageInfo.pageNum + 1,pageSize);
                    } else {
                        //Call the query method to query the data of the current page
                        queryByPage(page,pageSize);
                    }
                });
            }
        });
    }

</script>
</html>

The server

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 {
        //Set the encoding of requests and responses
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        //1. Get request parameters
        String start = req.getParameter("start");
        String pageSize = req.getParameter("pageSize");

        //2. Call the query method of the business layer according to the current Page number and the number of items displayed on each Page to get the paged Page object
        NewsService service = new NewsServiceImpl();
        Page page = service.pageQuery(Integer.parseInt(start), Integer.parseInt(pageSize));

        //3. Encapsulate PageInfo object
        PageInfo<List<News>> info = new PageInfo<>(page);

        //4. Convert the data to JSON
        String json = new ObjectMapper().writeValueAsString(info);

        //5. Respond the data to the client
        resp.getWriter().write(json);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}

Posted by nomanoma on Sat, 27 Jun 2020 18:55:02 -0700