天天看點

SpringMVC---Ajax使用

Ajax研究

文章目錄

  • ​​Ajax研究​​
  • ​​僞造AJAX​​
  • ​​jQuery.ajax​​
  • ​​1. 第一個ajax​​
  • ​​2. Springmvc實作​​
  • ​​3. 注冊提示效果​​
  • ​​Ajax總結​​

Ajax的核心是​

​XMLHttpRequest​

​對象(XHR){内置對象},XHR為伺服器發送請求和解析伺服器響應提供了接口,能夠以異步方式從伺服器擷取新資料

簡介
  • AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML)。
  • AJAx是一種無需重新加載整個頁面的情況下,能夠更新部分頁面的技術
  • AJAx不是一種新的程式設計語言,而是一種用于建立更好更快以及互動性更強的Web應用程式的技術
  • 傳統頁面(不适用ajax技術的頁面),想要更新内容或者送出一個表單,都需要重新加載整個頁面
  • 使用ajax技術頁面,通過在背景伺服器進行少量的資料交換,就可以實作異步局部更新
  • 使用Ajax,使用者可以建立接近本地桌面應用的直接、高可用、更豐富、更動态的Web使用者界面。

僞造AJAX

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script type="text/javascript">.onload=function f() {
        var myDate=new  Date();
        document.getElementById('currentTime').innerText=myDate.getTime()
    }
    
    function  LoadPage(){
        var  targetURL=document.getElementById('url').value;
        console.log(targetURL);
        document.getElementById('iframePosition').src=targetURL

    }</script>


<div>
    <p>請輸入要加載的位址:<span id="currentTime"></span></p>
    <p>
        <input id="url" type="text" value="https://www.baidu.com/"/>
        <input type="button" value="送出" onclick="LoadPage()">
    </p>
</div>

<div>
    <h3>加載頁面位置:</h3>
    <iframe id="iframePosition"style="width: 100%;height: 500px;"></iframe>
</div>

</body>
</html>      

利用AJAX可以做:

  • 注冊時,輸入使用者名自動檢測使用者是否已經存在
  • 登入時,提示使用者名密碼錯誤
  • 删除資料行時,将行id發送到背景,背景在資料庫中删除,資料庫删除成功後,子啊頁面DOM中将資料行删除

jQuery.ajax

  • Ajax的核心時​

    ​XMLHttpRequest​

    ​對象(XHR),XHR為伺服器發送請求和解析伺服器響應提供了接口,能夠以異步方式從伺服器擷取新資料
  • ​jQuery Ajax本質就是 XMLHttpRequest,對他進行了封裝,友善調用​

  • 通過 jQuery AJAX 方法,能夠使用HTTP GEt和HTTP post 從遠端伺服器上請求文本,HTML,XML或JSON-同時 能吧這些外部資料直接載入網頁的被選元素中。
  • jQuery 不是生産者,而是大自然搬運工。

jQuery.ajax(...)

部分參數:

url:請求位址

type:請求方式,GET、POST(1.9.0之後用method)

headers:請求頭

data:要發送的資料

contentType:即将發送資訊至伺服器的内容編碼類型(預設: "application/x-www-form-urlencoded; charset=UTF-8")

async:是否異步

timeout:設定請求逾時時間(毫秒)

beforeSend:發送請求前執行的函數(全局)

complete:完成之後執行的回調函數(全局)

success:成功之後執行的回調函數(全局)

error:失敗之後執行的回調函數(全局)

accepts:通過請求頭發送給伺服器,告訴伺服器目前用戶端可接受的資料類型

dataType:将伺服器端傳回的資料轉換成指定類型

"xml": 将伺服器端傳回的内容轉換成xml格式

"text": 将伺服器端傳回的内容轉換成普通文本格式

"html": 将伺服器端傳回的内容轉換成普通文本格式,在插入DOM中時,如果包含JavaScript标簽,則會嘗試去執行。

"script": 嘗試将傳回值當作JavaScript去執行,然後再将伺服器端傳回的内容轉換成普通文本格式

"json": 将伺服器端傳回的内容轉換成相應的JavaScript對象

"jsonp": JSONP 格式使用 JSONP 形式調用函數時,如 "myurl?callback=?" jQuery 将自動替換 ? 為正确的函數名,以執行回調函數

1. 第一個ajax

最原始的HttpServletResponse處理 , .最簡單 , 最通用

//第一種方式,伺服器要傳回一個字元串,直接使用response
    @RequestMapping("/a1")
    public void ajax(String name, HttpServletResponse response) throws IOException {
        if ("admin".equals(name)) {
            response.getWriter().print("true");
        } else {
            response.getWriter().print("false");
        }
    }      

3、導入jquery , 可以使用線上的CDN , 也可以下載下傳導入

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>      

前端部分

//所有參數

// url: 待載入頁面的Url位址 json

// data 待發送key/value 參數

// success 載入成功時回調函數

// data 封裝了伺服器的資料

// status 狀态

$.ajax({

url: "${pageContext.request.contextPath}/ajax/a1",

data: {'name': $("#txtName").val()},

success: function (data, status) {

console.log(data);

console.log(status)

}

});

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Ajax</title>
    <%--    路徑問題--%>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<script type="text/javascript">function a1() {
        //所有參數
        // url: 待載入頁面的Url位址 json
        // data  待發送key/value 參數
        // success  載入成功時回調函數
        // data 封裝了伺服器的資料
        // status 狀态
        $.ajax({
            url: "${pageContext.request.contextPath}/ajax/a1",
            data: {'name': $("#txtName").val()},
            success: function (data, status) {
                console.log(data);
                console.log(status)
            }
        });
//将文本輸出的指
        //發給伺服器
        //接收伺服器傳回的資料
    }</script>

使用者名

<input type="text" id="txtName" onblur="a1()">
</body>
</html>      

2. Springmvc實作

@RequestMapping("/a2")
@ResponseBody
public List<User> ajax2() {
    List<User> list = new ArrayList<User>();
    list.add(new User("1号", 3, "男"));
    list.add(new User("2号", 3, "男"));
    list.add(new User("3号", 3, "男"));
    return list; //由于@RestController注解,将list轉成json格式傳回
}      

前端頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Ajax</title>
    <%--    路徑問題--%>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<input type="button" id="btn" value="擷取資料">
<table width="80%" align="center">

    <tr>
        <td>姓名</td>
        <td>年齡</td>
        <td>性别</td>
    </tr>
    <tbody id="content">
    </tbody>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script >$(function () {
            $("#btn").click("${pageContext.request.contextPath}/ajax/a2",function (data) {
                $.post("${pageContext.request.contextPath}/ajax/a2",function (data) {
                    console.log(data)
                    var html="";
                    for (var i = 0; i <data.length ; i++) {
                        html+= "<tr>" +
                            "<td>" + data[i].name + "</td>" +
                            "<td>" + data[i].age + "</td>" +
                            "<td>" + data[i].sex + "</td>" +
                            "</tr>"
                    }
                    $("#content").html(html);
                });
            })
        })</script>

</table>
</body>
</html>      

成功實作了資料回顯!可以體會一下Ajax的好處!

3. 注冊提示效果

平時注冊時候,輸入框後面的實時提示怎麼做到的;如何優化

Controller

@RequestMapping("/a3")
@ResponseBody
public String ajax3(String name,String pwd) {
  String msg="";
  //模拟資料庫中存在資料
    if (name!=null){
        if ("admin".equals(name)){
            msg = "OK";
        }else {
            msg = "使用者名輸入錯誤";
        }
    }
    if (pwd!=null){
        if ("123456".equals(pwd)){
            msg = "OK";
        }else {
            msg = "密碼輸入有誤";
        }
    }
    return msg;
}      

前端 login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>function a1() {
            $.post({
                url: "${pageContext.request.contextPath}/ajax/a3",
                data: {'name': $("#name").val()},
                success: function (data) {
                    if (data.toString() == 'ok') {
                        $("#userInfo").css("color", "green")
                    } else {
                        $("#userInfo").css("color", "red")
                    }
                    $("#userInfo").html(data);
                }
            })

        }

        function a2() {
            $.post("${pageContext.request.contextPath}/ajax/a3",
                {'pwd': $("#pwd").val()}, function (data) {
                if (data.toString() == 'ok') {
                    $("#pwdInfo").css("color", "green")
                } else {
                    $("#pwdInfo").css("color", "red")
                }
                $("#pwdInfo").html(data);
            })
        }</script>
</head>
<body>
<p>
    使用者名
    <input type="text" id="name" onblur="a1()">
    <span id="userInfo"></span>
</p>
<p>
    密碼
    <input type="text" id="pwd" onblur="a2()">
    <span id="pwdInfo"></span>
</p>
</body>
</html>      
SpringMVC---Ajax使用

Ajax總結

使用Jquery需要導入Jquery,使用Vue導入vue,

  • 編寫對應的處理Controller,傳回消息或者字元串或者Json格式的資料
  • 編寫AJax請求
  1. URL:Controller請求
  2. data 鍵值對
  3. successL回調函數
<script>function a1() {
            $.post({
                url: "${pageContext.request.contextPath}/ajax/a3",
                data: {'name': $("#name").val()},
                success: function (data) {
                    if (data.toString() == 'ok') {
                        $("#userInfo").css("color", "green")
                    } else {
                        $("#userInfo").css("color", "red")
                    }
                    $("#userInfo").html(data);
                }
            })

        }

        function a2() {
            $.post("${pageContext.request.contextPath}/ajax/a3",
                {'pwd': $("#pwd").val()}, function (data) {
                if (data.toString() == 'ok') {
                    $("#pwdInfo").css("color", "green")
                } else {
                    $("#pwdInfo").css("color", "red")
                }
                $("#pwdInfo").html(data);
            })
        }</script>