1. 程式人生 > 實用技巧 >SpringMVC(3):AJAX

SpringMVC(3):AJAX

一,AJAX 簡介

  • AJAX = Asynchronous JavaScript and XML(非同步的 JavaScript 和 XML)
  • AJAX 不是新的程式語言,而是一種使用現有標準的新方法
  • AJAX 最大的優點是在不重新載入整個頁面的情況下,能與伺服器交換資料並更新部分網頁內容
  • AJAX 不需要任何瀏覽器外掛,但需要使用者允許JavaScript在瀏覽器上執行

二,用前端標籤偽造一個AJAX

傳統的網頁(即不用ajax技術的網頁),想要更新內容或者提交一個表單,都需要重新載入整個網頁,但是使用ajax技術的網頁,通過在後臺伺服器進行少量的資料交換,就可以實現非同步區域性更新。
我們可以使用前端的一個標籤來偽造一個ajax的樣子; iframe標籤

要求:在不重新整理網頁的情況下加載出百度

程式碼

 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 21 <p> 22 <h3>請輸入要載入的地址:</h3> 23 <input id="url" type="text" value="https://www.baidu.com/"/> 24 <input type="button" value="提交" onclick="LoadPage()"> 25
</p> 26 27 </div>
28 29 <div> 30 <h3>載入頁面位置:</h3> 31 <iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe> 32 </div> 33 34 </body> 35 </html>

執行結果

三,jQuery.Ajax 簡介

  • Ajax的核心是XMLHttpRequest物件(XHR)。XHR為向伺服器傳送請求和解析伺服器響應提供了介面。能夠以非同步方式從伺服器獲取新資料
  • jQuery 提供多個與 AJAX 有關的方法,通過 jQuery AJAX 方法,我們能夠使用 HTTP Get 和 HTTP Post 從遠端伺服器上請求文字、HTML、XML 或 JSON;同時我們能夠把這些外部資料直接載入網頁的被選元素中
  • jQuery 不是生產者,而是大自然搬運工;jQuery Ajax本質就是 XMLHttpRequest

四,程式碼小測試

使用jQuery時我們要先匯入jQuery的jar包

下載地址:https://mvnrepository.com/artifact/org.webjars.bower/jquery/3.4.1

1,使用最原始的HttpServletResponse處理

編寫一個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>

執行結果