SpringMVC(三)---AJAX

A, AJAX Introduction

  • AJAX = Asynchronous JavaScript and XML (Asynchronous JavaScript and XML)
  • AJAX is not a new programming language, but a new way to use existing standards
  • The biggest advantage is AJAX without reloading the entire page, and can exchange data with the server and update parts of the page content
  • AJAX does not require any browser plug-ins, but requires the user to allow the execution of JavaScript in the browser

Second, with the front end of a forged tag AJAX

Traditional web page (that is, without ajax technology web page), you want to update or submit a form, you need to reload the entire page, but the page using ajax technology, by a small amount of data exchange server in the background, you can achieve asynchronous locally update.
We can use a label to the front of a fake look of ajax; iframe tag

Requirements: Load a Baidu without refreshing the page

Code

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title>Shandx</title>
 6 </head>
 7 <body>
 8 
 9 <script type="text/javascript">
10 
11     function LoadPage(){
12         var targetUrl =  document.getElementById('url').value;
13         console.log(targetUrl);
14         document.getElementById("iframePosition").src = targetUrl;
15     }
16 
17 </script>
18 
19<div>
 20 is  
21 is      <P>
 22 is          <H3> enter the address to be loaded: </ H3>
 23 is          <INPUT ID = "URL" type = "text" value = "https://www.baidu.com/" />
 24          <INPUT type = "Button" value = "submit" the onclick = "the LoadPage ()">
 25      </ P>
 26 is  
27 </ div> 
28 29 <div> 30 <H3> the page is loaded position: </ h3 > 31 is <iframes ID = "iframePosition" style = "width: 100%; height: 500px;"> </ iframes> 32 </ div> 33 is 34 is </ body> 35 </html>

operation result

 

 

 

Three, jQuery.Ajax Profile

  • The core of Ajax is the XMLHttpRequest object (XHR). XHR resolving server to send a request and in response provides an interface to the server. Able to obtain new data from the server asynchronously
  •  providing a plurality of jQuery AJAX related method, by jQuery AJAX methods, we can use the HTTP Post requests and HTTP Get text, HTML, XML, or JSON from the remote server; the same time we are able to directly load these external data page is selected element
  •  jQuery is not a producer, but the nature porters; jQuery Ajax essentially XMLHttpRequest

Fourth, the Code Quiz

When we first imported using jQuery jQuery jar package

Download: https: //mvnrepository.com/artifact/org.webjars.bower/jquery/3.4.1

 

(1) using the most primitive processing HttpServletResponse

Write a Ajax Controller

 1 @Controller
 2 @RequestMapping("/ajax")
 3 public class AjaxController {
 4 
 5     @RequestMapping("/a1")
 6     public void ajax1(String name , HttpServletResponse response) throws IOException {
 7         if ("admin".equals(name)){
 8             response.getWriter().print("true");
 9         }else{
10             response.getWriter().print("false");
11         }
12     }
13 
14 }

编写index.jsp测试

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <head>
 3     <title>ajax</title>
 4     
 5     <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>
 6     <script>
 7    
 8   /* jQuery.post(...)   所有参数:
 9               url: 待载入页面的URL地址 (必填)
10              data: 待发送 Key/value 参数
11           success: 载入成功时回调函数
12             data:请求返回的数据
13             status:请求返回的状态*/
14          
15         function a1(){
16             $.post({
17                 url:"${pageContext.request.contextPath}/ajax/a1",
18                 data:{'name':$("#txtName").val()},
19                 success:function (data,status) {
20                     console.log(data);
21                     console.log(status);
22                 }
23             });
24         }
25 
26     </script>
27 </head>
28 <body>
29 
30 <%--onblur:失去焦点触发事件--%>
31 用户名:<input type="text" id="txtName" onblur="a1()"/>
32 
33 </body>

 

运行结果

(2)SpringMVC实现

 

编写一个Controller

 1 @RequestMapping("/a2")
 2     @ResponseBody
 3     public List<User> ajax2(){
 4         List<User> list = new ArrayList<User>();
 5         list.add(new User("钢铁侠",1,"男"));
 6         list.add(new User("蜘蛛侠",2,"男"));
 7         list.add(new User("闪电侠",3,"男"));
 8         return list;   //由于@ResponseBody注解,将list转成json格式返回
 9     }
10 ```
11 **编写index2.jsp测试**
12 
13 ```
14 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
15 <html>
16 <head>
17     <title>Title</title>
18 </head>
19 <body>
20 
21 <input type="button" id="btn" value="获取数据"/>
22 <table width="80%" align="center">
23     <tr>
24         <td>姓名</td>
25         <td>年龄</td>
26         <td>性别</td>
27     </tr>
28     <tbody id="content">
29     </tbody>
30 </table>
31 
32 <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>
33 
34 <script>
35     $(function () {
36         $("#btn").click(function () {
37             $.post("${pageContext.request.contextPath}/ajax/a2",function (data) {
38                 console.log(data);
39                 var html = "";
40                 for (var i=0;i<data.length;i++){
41                     html += "<tr>" +
42                         "<td>"+data[i].name + "</td>" +
43                         "<td>"+data[i].age + "</td>" +
44                         "<td>"+data[i].sex + "</td>" +
45                         "</tr>"
46                 }
47                 $("#content").html(html);
48             })
49         })
50     })
51 </script>
52 
53 </body>
54 </html>

运行结果

 

 

(3)注册提示

编写一个Controller

 1 @RequestMapping("/a3")
 2     @ResponseBody
 3     public String ajax3(String name,String pwd){
 4 
 5         String msg = "";
 6         //模拟数据库中存在数据
 7         if (name!=null){
 8             if ("admin".equals(name)){
 9                 msg = "OK";
10             }else {
11                 msg = "用户名输入错误";
12             }
13         }
14         if (pwd!=null){
15             if ("123456".equals(pwd)){
16                 msg = "OK";
17             }else {
18                 msg = "密码输入有误";
19             }
20         }
21         return msg; //由于@ResponseBody注解,将list转成json格式返回
22     }

编写index3.jsp测试

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>ajax</title>
 5     <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.min.js"></script>
 6     <script>
 7 
 8         function a1() {
 9             $.post({
10                 url: "${pageContext.request.contextPath}/ajax/a3",
11                 data: {'name': $("#name").val()},
12                 success: function (data) {
13                     if (data.toString() == 'OK') {
14                         $("#userInfo").css("color", "green");
15                     } else {
16                         $("#userInfo").css("color", "red");
17                     }
18                     $("#userInfo").html(data);
19                 }
20             });
21         }
22 
23         function a2() {
24             $.post({
25                 url: "${pageContext.request.contextPath}/ajax/a3",
26                 data: {'pwd': $("#pwd").val()},
27                 success: function (data) {
28                     if (data.toString() == 'OK') {
29                         $("#pwdInfo").css("color", "green");
30                     } else {
31                         $("#pwdInfo").css("color", "red");
32                     }
33                     $("#pwdInfo").html(data);
34 
35                 }
36             });
37         }
38 
39     </script>
40 </head>
41 <body>
42 <p>
43     用户名:<input type="text" id="name" onblur="a1()"/>
44     <span id="userInfo"></span>
45 </p>
46 <p>
47     密码:<input type="text" id="pwd" onblur="a2()"/>
48     <span id="pwdInfo"></span>
49 </p>
50 </body>
51 </html>

运行结果

 

Guess you like

Origin www.cnblogs.com/tqsh/p/11298013.html