Asynchronous request, please know about Ajax

1. Ajax overview

​ If the content of a traditional web page needs to be updated, the entire web page must be reloaded. Whenever a user sends a request to the server, even if only a little bit of partial content needs to be updated, the server will refresh the entire page. The disadvantages of this approach are:

  • Performance will be reduced (a little content, refresh the entire page!)

  • The user's operation page will be interrupted (the entire page is refreshed)

1) What is Ajax

Ajax stands for "Asynchronous Javascript And XML", which refers to a web development technology for creating interactive web applications. Ajax = Asynchronous JavaScript and XML.

Ajax is a technology that allows asynchronous communication with the server without refreshing the entire browser when the client interacts with the server

Insert picture description here

2) The role of Ajax

​ Ajax can make web pages update asynchronously . This means that it is possible to update a certain part of the web page (partial update) without reloading the entire web page .

Insert picture description here
3) Benefits of Ajax

  • Reduce the burden on the server and obtain data as needed.
  • No refresh to update the page, reducing the user's actual and psychological waiting time.
  • Only update part of the page, effectively use bandwidth
  • All major browsers support Ajax

4) Asynchronous and synchronous

  • How the browser accesses the server
    • Synchronous access: The client must wait for the response from the server, and no other operations can be performed during the waiting process
    • Asynchronous access: The client does not need to wait for the response of the service. During the waiting period, the browser can perform other operations

Insert picture description here

2. Implementation of ajax in JS mode (understand)

JS ajax: appeared the earliest. Use an object XmlHttpRequest object. Specially used for sending ajax requests and receiving responses

Use ajax to send requests, use ajax to receive responses, and use JS to refresh the page.

  • Disadvantages:

    • If you use JS's AJAX technology, in order to achieve simple functions, you need to write a lot of complex code.
    • The AJAX code of JS has poor browser compatibility.

Front-end JS code, just copy

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>new jsp</title>

    <script>
        function run() {
     
     
            //1.创建 核心对象
            var xmlhttp;

            //2.判断浏览器类型
            if (window.XMLHttpRequest) {
     
     
                xmlhttp=new XMLHttpRequest();
            } else {
     
     
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }



            //3.建立连接
            /**
             * 三个参数:
             *      1.请求方式 get post
             *      2.请求资源的路径
             *      3.是否为异步 是 or 否
             */
            xmlhttp.open("GET","/login?username=tom",true);

            //4.发送请求
            xmlhttp.send();

            //5.获取响应结果
            /**
             * 什么时候获取响应数据?
             *      在服务器响应成功后获取
             */
            //监听readyState状态改变
            xmlhttp.onreadystatechange=function() {
     
     
                //readyState==4 响应已经就绪, 200 访问成功
                if (xmlhttp.readyState==4 && xmlhttp.status==200) {
     
     
                    //获取响应数据
                    var text = xmlhttp.responseText;
                    alert(text);
                }
            }
        }
    </script>
</head>
<body>
    <input type="button" value="发送异步请求" onclick="run()"><br>
    局部刷新 <input type="text">
</body>
</html>

Backend Servlet

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    

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

        //1.获取请求数据
        String username = req.getParameter("username");

        //打印 username
        System.out.println(username);
        resp.getWriter().write(username);
    }

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

3. Ajax of jQuery framework

3.1 Introduction to ajax of JQuery framework

Jquery is an excellent js framework, which naturally encapsulates the native ajax of js, and the operation method of the encapsulated ajax is more concise and more powerful.

There are several jquery methods related to ajax operations, but there are three commonly used in development: POST, GET, AJAX

3.2 GET request method

Load information via remote HTTP GET request. This is a simple GET request function, if you need complex ajax parameter settings, please use $.ajax

Get request mode syntax

$.get(url,data,callback,type)

  • Parameter 1: urlrequest path
  • Parameter 2: dataThe data carried in the request
    Format: key=valueor {username='baby',pwd:666}
  • Parameter 3: callbackcallback function after successful response
  • Parameter 4: typeResponse data type text html xml json

Code example

//JQuery get方式发送异步请求
function run2() {
    
    
    //1.参数1 url
    var url = "/login";

    //2.参数2 数据
    var data = {
    
    username:"jack"};

    //3.发送get请求
    $.get(url,data,function (param) {
    
    
        //data响应回来的内容体
        alert("响应成功! 响应数据: " + param);
    },"text");
}

3.3 POST request method

Load information via remote HTTP POST request. This is a simple POST request function, if you need complex ajax parameter settings, please use $.ajax

Post request syntax

$ .post (url, data, callback
, type) inside the four parameters and get the same manner, is not the same as the different ways a request

Code example

//JQuery post方式发送异步请求
function run3() {
    
    
    //1.参数1 url
    var url = "/login";

    //2.参数2 数据
    var data = {
    
    username:"lucy"};

    //3.发送get请求
    $.post(url,data,function (param) {
    
    
    	//data响应回来的内容体
    	alert("响应成功! 响应数据: " + param);
    },"text");
}

3.4 Ajax request method

The $.ajax() method can set the underlying parameters in more detail. This method is usually used for requests that cannot be fulfilled by other methods.

Ajax request mode syntax:

  • Method 1: jQuery.ajax({[settings]})
  • Method 2: $.ajax(())

settings is an object in js literal form, the format is a key-value pair {name:value,name:value}, the commonly used name attribute names are as follows:

Code example

//Ajax方式 发送请求
function run4() {
    
    
 	$.ajax({
    
    
	 	url:"/login",
 		async:true, //是否异步
 		data:{
    
    username:"tom"},
 		type:"POST", //请求方式
 		dataType:"text", //返回数据的数据类型
 		success:function (param) {
    
    
 			alert("响应成功!! " + param)
 		},
 		error:function () {
    
    
 			alert("响应失败!!")
 		}
 	});
}

4. Case: Check whether the user name has been registered

Requirement: The user enters the user name, after the mouse is removed, the user name is judged, and the user name is prompted whether it is available

Insert picture description here
step:

  1. Prepare the Servlet, verify the user name, and return the result (whether it is available)
  2. For the page input box, bind the mouse removal event
  3. Make an asynchronous request and get the response result
  4. According to the result, dynamically add HTML code

Background Servlet

@WebServlet("/checkName")
public class CheckNameServelt extends HttpServlet {
    
    

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

        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //获取姓名
        String username = req.getParameter("username");

        //封装数据
        HashMap<String,Object> map = new HashMap<>();

        //判断用户是否存在
        if("tom".equals(username)){
    
    
            map.put("flag",true);
            map.put("msg","用户名已经被占用!");
            String data = JSON.toJSONString(map);
            resp.getWriter().print(data);
        }else{
    
    
            //用户名未被使用
            map.put("flag",false);
            map.put("msg","用户名可以使用!");
            String data = JSON.toJSONString(map);
            resp.getWriter().print(data);
        }
    }

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

Front-end JSP

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>new jsp</title>
    <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

    <script>
        $(function() {
     
     
            $("#username").blur(function () {
     
     

                //获取用户名
                var name = $(this).val();

                //判断用户名不为空
                if(name != null && name != ""){
     
     
                    $.ajax({
     
     
                        url:"/checkName",
                        type:"GET",
                        data:{
     
     username:name},
                        dataType:"json",
                        success:function (data) {
     
     
                            if(data.flag){
     
     
                                //设置span内容体
                                $("#spanMsg").html("<font color='red'>" + data.msg+ "</font>");

                            }else if(!data.flag){
     
     
                                $("#spanMsg").html("<font color='green'>"+ data.msg + "</font>");
                            }
                        },
                        error:function () {
     
     
                            alert("请求处理失败!")
                        }
                    });

                }
            })
        });

    </script>
</head>
<body>
<form action="#" method="post">

    用户名: <input type="text" id="username" name="username" placeholder="请输入用户名">
    <span id="spanMsg" style="color:red"></span><br>

    密码: <input type="text" name="password" placeholder="请输入密码"><br>
</form>

</body>
</html>

Case source download: Ajax-Sample Code

Guess you like

Origin blog.csdn.net/u012660464/article/details/114226791