Ajax for web development

Time:2022-5-2

Today, I will share with you the usefulness of Ajax technology in combination with several cases

Let’s first understand what AJAX is

Ajax: Technology of refreshing only partial pages

The full name of AJAX is asynchronous JavaScript and XML

AJAX is not a new programming language, but a new way to use existing standards

AJAX is a technology that can exchange data with the server and update some web pages without reloading the whole web page

The biggest advantage of AJAX is that the page has no refresh and the user experience is very good. It also uses asynchronous communication with the server, which has faster response ability

Concepts of synchronization and asynchrony

In short, it can be understood in this way (or by yourself):

  • Synchronization: wash your face and then boil water
  • Asynchronous: while washing my face, ask someone to boil water for me

 

Case 1: using Ajax to realize no refresh login

No refresh: do not refresh the whole page, but only refresh the part

The advantage of no refresh is to update only some pages, make effective use of bandwidth and improve user experience

Backend code:

/**
 *Process login function
 **/
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {

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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get form data
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        //Call biz to verify the database
        PrintWriter out = resp.getWriter();
        if("root".equals(account)&&"root123".equals(password)){
            out.println("yes");
        }else{
            out.println("no");
        }
    }
}

Front end JSP code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-3.3.1.js"></script>
</head>
<body>
<div>
    <p><input id="account" name="account"></p>
    <p><input id="password" name="password"></p>
    < button onclick = "login()" > login < / button >
</div>
<script>
    function login() {
        //Get the value of the page
        let account = $("#account").val()
        let password = $("#password").val()
        //Send the request via jQuery Ajax to the background login do

        //1. Using Ajax methods: both get and post are supported
        $.ajax({
            URL: "login. Do", // access address
            Data: {account, password}, // data carried
            Datatype: "text", // what kind of data do you want the background to give you
            Type: "get", // what request type
            success(resp){
                if (resp.trim() === "yes") {
                    Alert ("login succeeded")
                    location.href = "index.jsp"
                } else {
                    Alert ("login failed")
                }
            }, // success
            error(){

            }//Mistake
        })

        //2. Use get request (more convenient), and the same is true for get request
        /**
        $.get(
            //Request address
            "login.do",
            //Carry the past data and put it directly. The name is the name of the data
            {account, password},
            //This function will be called after the callback function request
            //Resp is the value given to me by the background
            function (resp) {
                //Trim to space
                //Contains contains
                if (resp.trim() === "yes") {
                    Alert ("login succeeded")
                    location.href = "index.jsp"
                } else {
                    Alert ("login failed")
                }
            },
            "Text" // I hope the background will give me ordinary text
        )
         **/

Case 2: use ajax to check whether the user name is repeated during registration in real time

Backend code:

@WebServlet("/find.do")
public class FindServlet extends HttpServlet {

    //Names that exist in the database
    List<String> list = new ArrayList<String>();

    {
        list. Add ("Xiao Ming");
        list. Add ("Xiaohuang");
        list. Add ("little black");
        list. Add ("little purple");
        list. Add ("little green");
    }

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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Go to database query
        String name = req.getParameter("name");
        boolean f=false;
        for (String n : list) {
            if(n.equals(name)){
                f=true;
                break;
            }
        }
        //Tell the front desk the result
        PrintWriter out = resp.getWriter();
        out.println(f);
    }

}

Front end JSP code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-3.3.1.js"></script>
    <style>
        #tip{
            color: red;
        }
    </style>
</head>
<body>
<p>< input id = "name" onkeyup = "yz()" type = "text" placeholder = "please enter your user name" > < span id = "tip" > < / span ></p>
< button id = "register" > register < / button >
<script>
    function yz(){
        //Get data
        let name=$("#name").val()
        //Send request
        $.get("find.do",{name},(resp)=>{
            if(resp.trim()==="true"){
                $("#tip"). Text ("user name already exists")
                $("#register").prop("disabled",true)
            }else{
                $("#tip").text("")
                $("#register").prop("disabled",false)
            }
        },"text")
    }
</script>
</body>
</html>

 

Case 3: using Ajax to realize automatic search prompt

Backend code:

@WebServlet("/search.do")
public class SearchServlet extends HttpServlet {

	//Product names that exist in the database
	List<String> list = new ArrayList<String>();

	{
		list. Add ("hey hey");
		list. Ha ("add");
		list. Add ("apple");
		list. Add ("ping an");
		list. Add ("Anle");
		list. Add ("ha ha");
		list. Add ("ha ha");
	}

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

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//Query the database select * from goods where name like '% key%'
		String keyWord = req.getParameter("keyWord");
		//Create a new collection
		List<String> ns = new ArrayList<>();
		for (String n : list) {
			if (n.contains(keyWord)) {
				ns.add(n);
			}
		}
		//Set the encoding of the response
		resp.setCharacterEncoding("utf-8");
		//You need to tell the front desk the results
		PrintWriter out = resp.getWriter();
		//Turn the collection into JSON
		// 1. Need to get conversion object
		ObjectMapper mapper = new ObjectMapper();
		// 2. Call method
		String str = mapper.writeValueAsString(ns);
		out.println(str);
	}
}

Front end JSP code:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-3.3.1.js"></script>
</head>
<body>
🔍<input id="keyWord" name="keyWord" onkeyup="search()">
<ul id="list">

</ul>
<script>
    function search(){
        //Get the value of the input box
        let keyWord=$("#keyWord").val()
        //Sent to the servlet responsible for retrieving the product name
        $.get("search.do",{keyWord},(resp)=>{
            //Clear the original option
            $("#list").empty()
            //Resp is now an array instead of a string
            for(let n of resp){//foreach
                $("#list").append("<li>"+n+"</li>")
            }
        },"json");
    }
    //json
    //The string format of the object. JSON has a fixed format
    //Turn object into JSON
    //Restore JSON to object
</script>
</body>
</html>

Thanks for reading^_^