Day10JavaWeb [Jquery advanced] Ajax***

learning target

If you submit the form to the server, when the server finishes processing, it responds to the browser, and you find that the browser flickers when it displays the page.
This method is not an asynchronous submission, but a synchronous submission. The flicker is the entire page refresh.

1. Able to understand the concept of asynchronous
2. Able to understand native js ajax
3. Able to use jQuery $.get()for access
4. Able to use jQuery $.post()for access
5. Able to use jQuery $.ajax()for access
6. Able to use the $.get()new signature of jQuery3.0 Access
7. Able to use the $.post()new signature of jQuery3.0 for access
8. Able to master the three data formats of
json 9. Able to use the json conversion tool Jackson to convert json format strings
10. Able to check whether the user name exists Heavy case
11. Cases that can complete automatic completion

Synchronous and asynchronous requests

(1) Mode of data transmission between browser and server
1: Synchronous mode
2: Asynchronous mode
Insert picture description here

(2) What is the difference between the two methods?
Synchronous request, when the server responds, the page is refreshed as a whole (response to the entire page)
asynchronous request, when the server responds, the page is partially refreshed (response to string or json)
(3) What are the advantages of asynchronous requests?
Asynchronous request can improve user experience
(4) What are the application scenarios of asynchronous request?
a: User name detection
b: Automatic completion of search
c: Partial refresh of the page

Native ajax programming (understand)

  • (1) The principle of traditional program operation: The
    user sends a request, the server accepts the request, and returns the data after processing. The browser accepts the response data and displays the data. At this time, there will be idle time between processing and acceptance, resulting in user waiting time
  • (2) The operating principle of Aajx's program is: the user sends a request, after the Ajax engine processes it, sends it to the server to accept the request, and returns the data Ajax after processing. The browser accepts the response data and displays the data. The browser can always interact with Ajax for communication, reducing processing time
    Insert picture description here
    web\0-base-ajax-index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
    <script type="text/javascript">
//            原生的ajax开发:
//            1)创建Ajax引擎对象
//            2)为Ajax引擎对象绑定监听(监听服务器已将数据响应给引擎)
//            3)绑定提交地址
//            4)发送请求
//            5)接受响应数据
//
        function  clickFn() {
     
     
            //1)创建Ajax引擎对象
           var xmlHttp = new XMLHttpRequest();
           //2)为Ajax引擎对象绑定监听(监听服务器已将数据响应给引擎)
            xmlHttp.onreadystatechange = function (ev) {
     
     
                //如果state值是4,说明收到响应数据
                //如果状态码是200.说明服务器正常响应
                if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
     
     
                   // 5)接受响应数据
                    //获取响应数据
                    alert(xmlHttp.responseText); //response.getWriter().write("hello")
                }
            }
            //3)绑定提交地址
            //参1:表示请求方式
            // 参2:表示服务器的资源访问路径,不用加项目名,
            // 参3:表示是否异步,true是异步

            xmlHttp.open("get","s1",true);
            //4)发送请求
            xmlHttp.send();
        }

    </script>

</head>
<body>
    <!--设计一个按钮,一点击这个按钮,就向服务器发出异步请求-->
    <input type="button" value="点我,发出异步请求" onclick="clickFn()"/>
</body>
</html>

src\com\wzx\pack01_ajax\BaseAjaxServlet.java

@WebServlet("/s1")
public class BaseAjaxServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //响应给浏览器
        System.out.println("s1 doGet");
        //响应
        response.getWriter().println("hello");
    }
}

Introduction to ajax of jQuery framework

  • (1) Why not use native Ajax programming?
    Large amount of code, inconvenient to use, encapsulated into a function, direct call
  • (2) Ajax function of jQuery framework
    Insert picture description here

$.get request-principle

  • (1) get function
    $.get(url, [data], [callback], [type])
  • url: indicates the access path of the server, such as: "s1"
  • data: indicates the parameters sent to the server, 格式: 1: "username=wzx&password=123"2: json string
  • callback: anonymous function, which means receiving the response sent by the server, this function is automatically executed
  • type: indicates the type of data the browser expects the server to send, 格式:"text" "json"
    (2) get request principle
 $.get(
	     "s2",
         "username=wzx&password=123",
		 function(data){
    
     //这个data就是服务器返回的字符串
			//处理数据
		 },
		 "text"
	 ); 
	 $.post(
	     "s2",
         "username=wzx&password=123",
		 function(data){
    
     //这个data就是服务器返回的字符串  var data = []
			//处理数据
		 },
		 "json"
	 );

	var url = "s2";
	var param =  "username=lft&password=123";
    var func = function(data){
    
    
	 
	};
	var type = "json";
	$.post(url,param,func,type);

$.get request-code implementation

(1) Call the get request in the click event
(2) Return json or string data on the server side
(3) Write business logic in the callback function
web\1-juqery-get_post_index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>

    <script type="text/javascript">
        function clickFn() {
     
     
            //向服务器发送异步请求
            $.post(
                "s2",
                "username=宝强x&password=123",
                function (data) {
     
     
                    alert(data);
                },
                "text"
            );
        }
    </script>


</head>
<body>
    <!--设计一个按钮,一点击这个按钮,就向服务器发出异步请求-->
    <input type="button" value="点我,发出jquery$.get异步请求" onclick="clickFn()"/>
</body>
</html>

src\com\wzx\pack02_jquery_ajax\Demo2Servlet.java

@WebServlet(name = "Demo2Servlet",urlPatterns = "/s2")
public class Demo2Servlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
         //解决请求乱码
        request.setCharacterEncoding("UTF-8");
           //1:接收参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        System.out.println("username:"+username);
        System.out.println("password:"+password);
//        System.out.println(1/0);
        //解决响应乱码
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("你好  ajax!");
    }
}

$.ajax request method***

(1) What is the $.ajaxrequest method?
This method combines the $.getsum $.postmethod into a request.
(2) How to call
$.ajax({键:值,键:值,键:值});
web\2-jquery-ajax-index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>

    <script type="text/javascript">
        function clickFn() {
     
     
          $.ajax({
     
     
              url:"s2",
              async:true,
              data:"username=bingbing&password=456",
              type:"post",
              dataType:"text",
              success:function (data) {
     
     
                  alert(data)
              },
              error:function () {
     
     
                    alert("服务器发生了错误")
              }
          });
        }
    </script>


</head>
<body>
    <!--设计一个按钮,一点击这个按钮,就向服务器发出异步请求-->
    <input type="button" value="点我,发出ajax异步请求" onclick="clickFn()"/>
</body>
</html>

  • The above function code for calling $.ajax is best copied, because the keys in the method cannot be modified at will, and the value can be modified.
  • If type is get, it means get request, otherwise it is post request

jquery3.0 new features ajax request

  • (1) What is the new feature of juqery3.0 GET/POST request
 $.get({
    
    键:值,键:值});
$.post({
    
    键:值,键:值});
  • Because the method specifies get and post, there is one less key than $.ajax, type:post or type:get, all others are the same.
  • 1.x is generally used in enterprises

Guess you like

Origin blog.csdn.net/u013621398/article/details/108659903