欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java中Ajax與Axios的使用小結(jié)

 更新時間:2024年02月01日 16:23:21   作者:是程序喵呀  
在項目中我們經(jīng)常會遇到需要向請求頭中添加消息的場景,本文主要介紹了java中Ajax與Axios的使用小結(jié),文中通過示例代碼介紹的非常詳細,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1,Ajax

1.1 概述

==AJAX (Asynchronous JavaScript And XML):異步的 JavaScript 和 XML。==

我們先來說概念中的 JavaScript 和 XML,JavaScript 表明該技術(shù)和前端相關(guān);XML 是指以此進行數(shù)據(jù)交換。而這兩個我們之前都學(xué)習(xí)過。

1.1.1 作用

AJAX 作用有以下兩方面:

  • 與服務(wù)器進行數(shù)據(jù)交換:通過AJAX可以給服務(wù)器發(fā)送請求,服務(wù)器將數(shù)據(jù)直接響應(yīng)回給瀏覽器。如下圖

我們先來看之前做功能的流程,如下圖:

如上圖,Servlet 調(diào)用完業(yè)務(wù)邏輯層后將數(shù)據(jù)存儲到域?qū)ο笾?,然后跳轉(zhuǎn)到指定的 jsp 頁面,在頁面上使用 EL表達式 和 JSTL 標(biāo)簽庫進行數(shù)據(jù)的展示。

而我們學(xué)習(xí)了AJAX 后,就可以==使用AJAX和服務(wù)器進行通信,以達到使用 HTML+AJAX來替換JSP頁面==了。如下圖,瀏覽器發(fā)送請求servlet,servlet 調(diào)用完業(yè)務(wù)邏輯層后將數(shù)據(jù)直接響應(yīng)回給瀏覽器頁面,頁面使用 HTML 來進行數(shù)據(jù)展示。

  • 異步交互:可以在==不重新加載整個頁面==的情況下,與服務(wù)器交換數(shù)據(jù)并==更新部分網(wǎng)頁==的技術(shù),如:搜索聯(lián)想、用戶名是否可用校驗,等等…

上圖所示的效果我們經(jīng)常見到,在我們輸入一些關(guān)鍵字(例如 奧運)后就會在下面聯(lián)想出相關(guān)的內(nèi)容,而聯(lián)想出來的這部分?jǐn)?shù)據(jù)肯定是存儲在百度的服務(wù)器上,而我們并沒有看出頁面重新刷新,這就是 ==更新局部頁面== 的效果。再如下圖:

我們在用戶名的輸入框輸入用戶名,當(dāng)輸入框一失去焦點,如果用戶名已經(jīng)被占用就會在下方展示提示的信息;在這整個過程中也沒有頁面的刷新,只是在局部展示出了提示信息,這就是 ==更新局部頁面== 的效果。

1.1.2 同步和異步

知道了局部刷新后,接下來我們再聊聊同步和異步:

  • 同步發(fā)送請求過程如下

瀏覽器頁面在發(fā)送請求給服務(wù)器,在服務(wù)器處理請求的過程中,瀏覽器頁面不能做其他的操作。只能等到服務(wù)器響應(yīng)結(jié)束后才能,瀏覽器頁面才能繼續(xù)做其他的操作。

  • 異步發(fā)送請求過程如下

    瀏覽器頁面發(fā)送請求給服務(wù)器,在服務(wù)器處理請求的過程中,瀏覽器頁面還可以做其他的操作。

1.2 快速入門

1.2.1 服務(wù)端實現(xiàn)

在項目的創(chuàng)建 com.itheima.web.servlet ,并在該包下創(chuàng)建名為 AjaxServlet 的servlet

@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 響應(yīng)數(shù)據(jù)
        response.getWriter().write("hello ajax~");
    }
?
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

1.2.2 客戶端實現(xiàn)

在 webapp 下創(chuàng)建名為 01-ajax-demo1.html 的頁面,在該頁面書寫 ajax 代碼

  • 創(chuàng)建核心對象,不同的瀏覽器創(chuàng)建的對象是不同的

     var xhttp;
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
  • 發(fā)送請求

    //建立連接
    xhttp.open("GET", "http://localhost:8080/ajax-demo/ajaxServlet");
    //發(fā)送請求
    xhttp.send();
  • 獲取響應(yīng)

    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            // 通過 this.responseText 可以獲取到服務(wù)端響應(yīng)的數(shù)據(jù)
            alert(this.responseText);
        }
    };

完整代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
?
<script>
    //1. 創(chuàng)建核心對象
    var xhttp;
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //2. 發(fā)送請求
    xhttp.open("GET", "http://localhost:8080/ajax-demo/ajaxServlet");
    xhttp.send();
?
    //3. 獲取響應(yīng)
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            alert(this.responseText);
        }
    };
</script>
</body>
</html>

1.2.3 測試

在瀏覽器地址欄輸入 http://localhost:8080/ajax-demo/01-ajax-demo1.html ,在 01-ajax-demo1.html加載的時候就會發(fā)送 ajax 請求,效果如下

我們可以通過 開發(fā)者模式 查看發(fā)送的 AJAX 請求。在瀏覽器上按 F12 快捷鍵

這個是查看所有的請求,如果我們只是想看 異步請求的話,點擊上圖中 All 旁邊的 XHR,會發(fā)現(xiàn)只展示 Type 是 xhr 的請求。如下圖:

1.3 案例

需求:在完成用戶注冊時,當(dāng)用戶名輸入框失去焦點時,校驗用戶名是否在數(shù)據(jù)庫已存在

1.3.1 分析

  • 前端完成的邏輯

    給用戶名輸入框綁定光標(biāo)失去焦點事件 onblur

    發(fā)送 ajax請求,攜帶username參數(shù)

    處理響應(yīng):是否顯示提示信息

  • 后端完成的邏輯

    接收用戶名

    調(diào)用service查詢User。此案例是為了演示前后端異步交互,所以此處我們不做業(yè)務(wù)邏輯處理

    返回標(biāo)記

整體流程如下:

1.3.2 后端實現(xiàn)

在 com.ithiema.web.servlet 包中定義名為 SelectUserServlet 的servlet。代碼如下:

@WebServlet("/selectUserServlet")
public class SelectUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 接收用戶名
        String username = request.getParameter("username");
        //2. 調(diào)用service查詢User對象,此處不進行業(yè)務(wù)邏輯處理,直接給 flag 賦值為 true,表明用戶名占用
        boolean flag = true;
        //3. 響應(yīng)標(biāo)記
        response.getWriter().write("" + flag);
    }
?
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

1.3.3 前端實現(xiàn)

將 04-資料\1. 驗證用戶名案例\1. 靜態(tài)頁面 下的文件整體拷貝到項目下 webapp 下。并在 register.html 頁面的 body 結(jié)束標(biāo)簽前編寫 script 標(biāo)簽,在該標(biāo)簽中實現(xiàn)如下邏輯

第一步:給用戶名輸入框綁定光標(biāo)失去焦點事件 onblur

//1. 給用戶名輸入框綁定 失去焦點事件
document.getElementById("username").onblur = function () {
    
}

第二步:發(fā)送 ajax請求,攜帶username參數(shù)

在 第一步 綁定的匿名函數(shù)中書寫發(fā)送 ajax 請求的代碼

//2. 發(fā)送ajax請求
//2.1. 創(chuàng)建核心對象
var xhttp;
if (window.XMLHttpRequest) {
    xhttp = new XMLHttpRequest();
} else {
    // code for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.2. 發(fā)送請求
xhttp.open("GET", "http://localhost:8080/ajax-demo/selectUserServlet);
xhttp.send();
?
//2.3. 獲取響應(yīng)
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        //處理響應(yīng)的結(jié)果
    }
};

由于我們發(fā)送的是 GET 請求,所以需要在 URL 后拼接從輸入框獲取的用戶名數(shù)據(jù)。而我們在 第一步 綁定的匿名函數(shù)中通過以下代碼可以獲取用戶名數(shù)據(jù)

// 獲取用戶名的值
var username = this.value;  //this : 給誰綁定的事件,this就代表誰

而攜帶數(shù)據(jù)需要將 URL 修改為:

xhttp.open("GET", "http://localhost:8080/ajax-demo/selectUserServlet?username="+username);

第三步:處理響應(yīng):是否顯示提示信息

當(dāng) this.readyState == 4 && this.status == 200 條件滿足時,說明已經(jīng)成功響應(yīng)數(shù)據(jù)了。

此時需要判斷響應(yīng)的數(shù)據(jù)是否是 "true" 字符串,如果是說明用戶名已經(jīng)占用給出錯誤提示;如果不是說明用戶名未被占用清除錯誤提示。代碼如下

//判斷
if(this.responseText == "true"){
    //用戶名存在,顯示提示信息
    document.getElementById("username_err").style.display = '';
}else {
    //用戶名不存在 ,清楚提示信息
    document.getElementById("username_err").style.display = 'none';
}

綜上所述,前端完成代碼如下:

//1. 給用戶名輸入框綁定 失去焦點事件
document.getElementById("username").onblur = function () {
    //2. 發(fā)送ajax請求
    // 獲取用戶名的值
    var username = this.value;
?
    //2.1. 創(chuàng)建核心對象
    var xhttp;
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //2.2. 發(fā)送請求
    xhttp.open("GET", "http://localhost:8080/ajax-demo/selectUserServlet?username="+username);
    xhttp.send();
?
    //2.3. 獲取響應(yīng)
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            //alert(this.responseText);
            //判斷
            if(this.responseText == "true"){
                //用戶名存在,顯示提示信息
                document.getElementById("username_err").style.display = '';
            }else {
                //用戶名不存在 ,清楚提示信息
                document.getElementById("username_err").style.display = 'none';
            }
        }
    };
}

2,axios

Axios 對原生的AJAX進行封裝,簡化書寫。

Axios官網(wǎng)是:https://www.axios-http.cn

2.1 基本使用

axios 使用是比較簡單的,分為以下兩步:

  • 引入 axios 的 js 文件

    <script src="js/axios-0.18.0.js"></script>
  • 使用axios 發(fā)送請求,并獲取響應(yīng)結(jié)果

    • 發(fā)送 get 請求

      axios({
          method:"get",
          url:"http://localhost:8080/ajax-demo1/aJAXDemo1?username=zhangsan"
      }).then(function (resp){
          alert(resp.data);
      })
    • 發(fā)送 post 請求

      axios({
          method:"post",
          url:"http://localhost:8080/ajax-demo1/aJAXDemo1",
          data:"username=zhangsan"
      }).then(function (resp){
          alert(resp.data);
      });

axios() 是用來發(fā)送異步請求的,小括號中使用 js 對象傳遞請求相關(guān)的參數(shù):

  • method 屬性:用來設(shè)置請求方式的。取值為 get 或者 post

  • url 屬性:用來書寫請求的資源路徑。如果是 get 請求,需要將請求參數(shù)拼接到路徑的后面,格式為: url?參數(shù)名=參數(shù)值&參數(shù)名2=參數(shù)值2。

  • data 屬性:作為請求體被發(fā)送的數(shù)據(jù)。也就是說如果是 post 請求的話,數(shù)據(jù)需要作為 data 屬性的值。

then() 需要傳遞一個匿名函數(shù)。我們將 then() 中傳遞的匿名函數(shù)稱為 ==回調(diào)函數(shù)==,意思是該匿名函數(shù)在發(fā)送請求時不會被調(diào)用,而是在成功響應(yīng)后調(diào)用的函數(shù)。而該回調(diào)函數(shù)中的 resp 參數(shù)是對響應(yīng)的數(shù)據(jù)進行封裝的對象,通過 resp.data 可以獲取到響應(yīng)的數(shù)據(jù)。

2.2 快速入門

2.2.1 后端實現(xiàn)

定義一個用于接收請求的servlet,代碼如下:

@WebServlet("/axiosServlet")
public class AxiosServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get...");
        //1. 接收請求參數(shù)
        String username = request.getParameter("username");
        System.out.println(username);
        //2. 響應(yīng)數(shù)據(jù)
        response.getWriter().write("hello Axios~");
    }
?
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("post...");
        this.doGet(request, response);
    }
}

2.2.2 前端實現(xiàn)

  • 引入 js 文件

    <script src="js/axios-0.18.0.js"></script>
  • 發(fā)送 ajax 請求

    • get 請求

      axios({
          method:"get",
          url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
      }).then(function (resp) {
          alert(resp.data);
      })
    • post 請求

      axios({
          method:"post",
          url:"http://localhost:8080/ajax-demo/axiosServlet",
          data:"username=zhangsan"
      }).then(function (resp) {
          alert(resp.data);
      })

整體頁面代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
?
<script src="js/axios-0.18.0.js"></script>
<script>
    //1. get
   /* axios({
        method:"get",
        url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
    }).then(function (resp) {
        alert(resp.data);
    })*/
?
    //2. post  在js中{} 表示一個js對象,而這個js對象中有三個屬性
    axios({
        method:"post",
        url:"http://localhost:8080/ajax-demo/axiosServlet",
        data:"username=zhangsan"
    }).then(function (resp) {
        alert(resp.data);
    })
</script>
</body>
</html>

2.3 請求方法別名

為了方便起見, Axios 已經(jīng)為所有支持的請求方法提供了別名。如下:

  • get 請求 : axios.get(url[,config])

  • delete 請求 : axios.delete(url[,config])

  • head 請求 : axios.head(url[,config])

  • options 請求 : axios.option(url[,config])

  • post 請求:axios.post(url[,data[,config])

  • put 請求:axios.put(url[,data[,config])

  • patch 請求:axios.patch(url[,data[,config])

而我們只關(guān)注 get 請求和 post 請求。

入門案例中的 get 請求代碼可以改為如下:

axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan").then(function (resp) {
    alert(resp.data);
});

入門案例中的 post 請求代碼可以改為如下:

axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=zhangsan").then(function (resp) {
    alert(resp.data);
})

到此這篇關(guān)于java中Ajax與Axios的使用小結(jié)的文章就介紹到這了,更多相關(guān)java Ajax與Axios內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論