Ajax&JSON in the second phase of java

Keywords: Java Front-end Database

1, Ajax

(1) Introduction to Ajax

         1. Introduction to Ajax

         Ajax is a web development technology to create interactive web applications. Is a technology for creating fast dynamic web pages.

         Ajax is a technology that can update some web pages without reloading the whole web page.

         2. Difference between synchronous mode and asynchronous mode

         ① Send request in synchronization mode:

         To send a request, you need to wait for the response to return before you can send the next request. If the request has no response and cannot send the next request, the client will be in the process of waiting all the time.

         ② Send request asynchronously

         When you send a request, you don't need to wait for the response to return. You can send the next request at any time, that is, you don't need to wait

(2) Implementing asynchrony in JS native mode

         1. Implementation steps

         ① Define an XMLHttpRequest core object xhr;

         ② Provide the access method, URL, etc. for the current object through the xhr.open method

         ③ Send the current request to the specified URL

         ④ Receive the return value and process it

         2. Case

         The foreground page sends an Ajax request to the background through a button. After the background completes the processing, the foreground page responds with a text message displayed on the page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-3.6.0.min.js"></script>
    <script>
        function demo() {
            //Create core object
            var xmlhttp = new XMLHttpRequest();
            //Provide the access method and URL path to the current object through the core object method
            xmlhttp.open("GET","jsAjax?name=name",true);
            //Send the current request to the specified URL
            xmlhttp.send();
            //Receive return value processing
            xmlhttp.onreadystatechange=function () {
                if(xmlhttp.readyState==4&&xmlhttp.status==200){
                    var msg = xmlhttp.responseText;
                    document.getElementById("msg").innerHTML=msg;
                }
            }
        }
    </script>
</head>
<body>
<div id="msg"></div>
<input type="button" value="Send request" onclick="demo()">
</body>
</html>
package com.offcn.demo01;

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("/jsAjax")
public class Demo04 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String nmae = req.getParameter("name");
        resp.getWriter().write("Response successful");
    }
}

(3) Asynchronous implementation in jQuery mode

         jQuery is an excellent JS framework. It naturally encapsulates the native Ajax of JS. The encapsulated Ajax has simpler operation methods, more powerful functions, and is also the most commonly used. It has simple syntax structure and good code readability.

         There are three common jQuery methods related to Ajax operations:

 

         1. Ajax request

         Syntax format:

     

$.ajax({
    url:"",
    data:{},
    type:"post/get",
    async:true,
    dataType:"text",
    success:function(obj){
        
    },
    error:function(){
        
    }
})

         Attribute resolution:

 

         matters needing attention:

         ① Each attribute should be followed by an English comma, and the last one should not be used

         ② Each attribute exists in the form of key value pairs, separated by English colons

         ③ data: {} is a special writing method. The value is a {}, which is stored with key value pairs

         ④ The above attributes have no sequence requirements

         2. get request

         Syntax format:

$.get(url,[data],[callback],[type]);

         Attribute resolution:

 

         matters needing attention:

         This writing function is the same as $. ajax, but the attribute order is strictly required.

         3. post request

         Syntax format:

$.post(url,[data],[callback],[type]);

         Attribute resolution:

 

         matters needing attention:

         This writing function is the same as $. ajax, but the attribute order is strictly required.

         4. Similarities and differences of $. ajax, $. get, $. post

         The same point: they are all jQuery encapsulated methods to realize asynchronous interaction.

         difference:

        $. ajax() is the first encapsulation of jQuery. It is a little troublesome to use, but it is powerful. It covers get and post requests. It has the ability of error debugging, and the writing order can be changed.

        $. post() and $. get() are the second encapsulation of Ajax by jQuery. Because the writing method of $. Ajax() is too cumbersome, it is simplified to $. post() and $. get(). The functions are the same without difference, but the writing method requires higher requirements and the order cannot be changed.

(4) Introduction to return value types of Ajax

         XML: too cumbersome to use

         HTML: the essence of a web page is the same as the returned text. There is no difference. Text is generally used instead.

         Script: returns the script directly

         Text: string type, which returns the directly received string

         Jason: the return is a js object, which can be operated directly in the script, which is very convenient

         Json p: just like Jason, it supports cross domain access.

2, JSON

(1) JSON data format

         1. JSON introduction

         JSON is a lightweight data exchange format. It is based on a subset of ECMAScript and uses a text format completely independent of the programming language to store and represent data. Introduction and clear hierarchy make JSON an ideal data exchange language. It is easy for people to read and write, but also easy for machine analysis and generation, and effectively improves the network transmission efficiency.

         2. JSON syntax format

         There are three kinds of syntax for JSON objects: object, array and mixed mode

         3. JSON format writing specification

         ① Write with {} and [] where {} represents the object type and [] represents the array type

         ② Each group of data in the object type is separated by commas, and the keywords and values in each group are separated by colons

         ③ Each value in the array type is separated by a comma, and the last value is not followed by a comma

(2) Application of JSON data

         The json conversion tool directly converts java objects or collections into json format strings through some jar toolkits encapsulated in java.

         1. Common json conversion tools

 

         2. Use steps

         ① Import json related jar packages

         ② Create a java object or collection

         ③ Use the writeValueAsString method of jackson's ObjectMapper object for conversion

package com.offcn.demo01;

import com.fasterxml.jackson.databind.ObjectMapper;

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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/jacksondemo")
public class Demo03 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        User u = new User("Zhang San",10);
        List<User> list = new ArrayList<>();
        list.add(new User("Li Si",12));
        list.add(new User("Wang Wu",18));
        list.add(new User("Zhao Liu",19));
        Map<String,User> map = new HashMap<>();
        map.put("u1",new User("Li Si",12));
        map.put("u2",new User("Wang Wu",16));
        map.put("u3",new User("Zhao Liu",18));
        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString(map);
        resp.getWriter().println(s);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="button" value="send out" id="btn">
</body>
<script src="js/jquery-3.6.0.min.js"></script>
<script>
    $(function () {
        $("#btn").click(function () {
            $.get("jacksondemo",function (obj) {
                console.log(obj)
                console.log(obj.u1.name)
            },"json")
        })
    })
</script>
</html>

Posted by Dysan on Sun, 28 Nov 2021 01:18:13 -0800