JavaWeb中異步交互的關(guān)鍵Ajax詳解
1,Ajax 概述
AJAX
(Asynchronous JavaScript And XML):異步的 JavaScript 和 XML。
我們先來說概念中的 JavaScript
和 XML
,JavaScript
表明該技術(shù)和前端相關(guān);XML
是指以此進(jìn)行數(shù)據(jù)交換
1.1 作用
AJAX 作用有以下兩方面:
與服務(wù)器進(jìn)行數(shù)據(jù)交換:通過AJAX可以給服務(wù)器發(fā)送請(qǐng)求,服務(wù)器將數(shù)據(jù)直接響應(yīng)回給瀏覽器。如下圖
我們先來看之前做功能的流程,如下圖:
如上圖,Servlet
調(diào)用完業(yè)務(wù)邏輯層后將數(shù)據(jù)存儲(chǔ)到域?qū)ο笾?,然后跳轉(zhuǎn)到指定的 jsp
頁面,在頁面上使用 EL表達(dá)式
和 JSTL
標(biāo)簽庫進(jìn)行數(shù)據(jù)的展示。
而我們學(xué)習(xí)了AJAX 后,就可以使用AJAX和服務(wù)器進(jìn)行通信,以達(dá)到使用 HTML+AJAX來替換JSP頁面了。如下圖,瀏覽器發(fā)送請(qǐng)求servlet,servlet 調(diào)用完業(yè)務(wù)邏輯層后將數(shù)據(jù)直接響應(yīng)回給瀏覽器頁面,頁面使用 HTML 來進(jìn)行數(shù)據(jù)展示。
異步交互:可以在不重新加載整個(gè)頁面的情況下,與服務(wù)器交換數(shù)據(jù)并更新部分網(wǎng)頁的技術(shù),如:搜索聯(lián)想、用戶名是否可用校驗(yàn),等等…
上圖所示的效果我們經(jīng)常見到,在我們輸入一些關(guān)鍵字(例如 奧運(yùn))后就會(huì)在下面聯(lián)想出相關(guān)的內(nèi)容,而聯(lián)想出來的這部分?jǐn)?shù)據(jù)肯定是存儲(chǔ)在百度的服務(wù)器上,而我們并沒有看出頁面重新刷新,這就是 更新局部頁面 的效果
1.2 同步和異步
知道了局部刷新后,接下來我們?cè)倭牧耐胶彤惒?
同步發(fā)送請(qǐng)求過程如下
? 瀏覽器頁面在發(fā)送請(qǐng)求給服務(wù)器,在服務(wù)器處理請(qǐng)求的過程中,瀏覽器頁面不能做其他的操作。只能等到服務(wù)器響應(yīng)結(jié)束后才能,瀏覽器頁面才能繼續(xù)做其他的操作。
異步發(fā)送請(qǐng)求過程如下
瀏覽器頁面發(fā)送請(qǐng)求給服務(wù)器,在服務(wù)器處理請(qǐng)求的過程中,瀏覽器頁面還可以做其他的操作。
1.3 案例
需求:在完成用戶注冊(cè)時(shí),當(dāng)用戶名輸入框失去焦點(diǎn)時(shí),校驗(yàn)用戶名是否在數(shù)據(jù)庫已存在
1.3.1 分析
前端完成的邏輯
- 給用戶名輸入框綁定光標(biāo)失去焦點(diǎn)事件
onblur
- 發(fā)送 ajax請(qǐng)求,攜帶username參數(shù)
- 處理響應(yīng):是否顯示提示信息
后端完成的邏輯
- 接收用戶名
- 調(diào)用service查詢User。此案例是為了演示前后端異步交互,所以此處我們不做業(yè)務(wù)邏輯處理
- 返回標(biāo)記
整體流程如下:
1.3.2 后端實(shí)現(xiàn)
定義名為 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對(duì)象,此處不進(jìn)行業(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 前端實(shí)現(xiàn)
將 04-資料\1. 驗(yàn)證用戶名案例\1. 靜態(tài)頁面 下的文件整體拷貝到項(xiàng)目下 webapp
下。并在 register.html
頁面的 body
結(jié)束標(biāo)簽前編寫 script
標(biāo)簽,在該標(biāo)簽中實(shí)現(xiàn)如下邏輯
第一步:給用戶名輸入框綁定光標(biāo)失去焦點(diǎn)事件 onblur
第二步:發(fā)送 ajax請(qǐng)求,攜帶username參數(shù)
在 第一步 綁定的匿名函數(shù)中書寫發(fā)送 ajax 請(qǐng)求的代碼
由于我們發(fā)送的是 GET 請(qǐng)求,所以需要在 URL 后拼接從輸入框獲取的用戶名數(shù)據(jù)。而我們?cè)?第一步 綁定的匿名函數(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
條件滿足時(shí),說明已經(jīng)成功響應(yīng)數(shù)據(jù)了。
此時(shí)需要判斷響應(yīng)的數(shù)據(jù)是否是 “true” 字符串,如果是說明用戶名已經(jīng)占用給出錯(cuò)誤提示;如果不是說明用戶名未被占用清除錯(cuò)誤提示
綜上所述,前端完成代碼如下:
//1. 給用戶名輸入框綁定 失去焦點(diǎn)事件 document.getElementById("username").onblur = function () { //2. 發(fā)送ajax請(qǐng)求 // 獲取用戶名的值 var username = this.value; //2.1. 創(chuàng)建核心對(duì)象 var xhttp; if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //2.2. 發(fā)送請(qǐng)求 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 對(duì)原生的AJAX進(jìn)行封裝,簡化書寫。
Axios官網(wǎng)是:https://www.axios-http.cn
2.1 基本使用
axios 使用是比較簡單的,分為以下兩步:
引入 axios 的 js 文件
<script src="js/axios-0.18.0.js"></script>
使用axios 發(fā)送請(qǐng)求,并獲取響應(yīng)結(jié)果
發(fā)送 get 請(qǐng)求
axios({ method:"get", url:"http://localhost:8080/ajax-demo1/aJAXDemo1?username=zhangsan" }).then(function (resp){ alert(resp.data); })
發(fā)送 post 請(qǐng)求
axios({ method:"post", url:"http://localhost:8080/ajax-demo1/aJAXDemo1", data:"username=zhangsan" }).then(function (resp){ alert(resp.data); });
axios()
是用來發(fā)送異步請(qǐng)求的,小括號(hào)中使用 js 對(duì)象傳遞請(qǐng)求相關(guān)的參數(shù):
- method 屬性:用來設(shè)置請(qǐng)求方式的。取值為 get 或者 post。
- url 屬性:用來書寫請(qǐng)求的資源路徑。如果是 get 請(qǐng)求,需要將請(qǐng)求參數(shù)拼接到路徑的后面,格式為: url?參數(shù)名=參數(shù)值&參數(shù)名2=參數(shù)值2。
- data 屬性:作為請(qǐng)求體被發(fā)送的數(shù)據(jù)。也就是說如果是 post 請(qǐng)求的話,數(shù)據(jù)需要作為 data 屬性的值。
then()
需要傳遞一個(gè)匿名函數(shù)。我們將 then()
中傳遞的匿名函數(shù)稱為 回調(diào)函數(shù),意思是該匿名函數(shù)在發(fā)送請(qǐng)求時(shí)不會(huì)被調(diào)用,而是在成功響應(yīng)后調(diào)用的函數(shù)。而該回調(diào)函數(shù)中的 resp
參數(shù)是對(duì)響應(yīng)的數(shù)據(jù)進(jìn)行封裝的對(duì)象,通過 resp.data
可以獲取到響應(yīng)的數(shù)據(jù)。
2.2 快速入門
2.2.1 后端實(shí)現(xiàn)
定義一個(gè)用于接收請(qǐng)求的servlet,代碼如下:
@WebServlet("/axiosServlet") public class AxiosServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("get..."); //1. 接收請(qǐng)求參數(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 前端實(shí)現(xiàn)
引入 js 文件
<script src="js/axios-0.18.0.js"></script>
發(fā)送 ajax 請(qǐng)求
get 請(qǐng)求
axios({ method:"get", url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan" }).then(function (resp) { alert(resp.data); })
post 請(qǐng)求
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中{} 表示一個(gè)js對(duì)象,而這個(gè)js對(duì)象中有三個(gè)屬性 axios({ method:"post", url:"http://localhost:8080/ajax-demo/axiosServlet", data:"username=zhangsan" }).then(function (resp) { alert(resp.data); }) </script> </body> </html>
2.3 請(qǐng)求方法別名
為了方便起見, Axios 已經(jīng)為所有支持的請(qǐng)求方法提供了別名。如下:
get
請(qǐng)求 :axios.get(url[,config])
delete
請(qǐng)求 :axios.delete(url[,config])
head
請(qǐng)求 :axios.head(url[,config])
options
請(qǐng)求 :axios.option(url[,config])
post
請(qǐng)求:axios.post(url[,data[,config])
put
請(qǐng)求:axios.put(url[,data[,config])
patch
請(qǐng)求:axios.patch(url[,data[,config])
而我們只關(guān)注 get
請(qǐng)求和 post
請(qǐng)求。
入門案例中的 get
請(qǐng)求代碼可以改為如下:
axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan").then(function (resp) { alert(resp.data); });
案例中的 post
請(qǐng)求代碼可以改為如下:
axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=zhangsan").then(function (resp) { alert(resp.data); })
總結(jié)
到此這篇關(guān)于JavaWeb中異步交互的關(guān)鍵Ajax的文章就介紹到這了,更多相關(guān)JavaWeb異步交互Ajax內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringMVC中Json數(shù)據(jù)格式轉(zhuǎn)換
本文主要介紹了SpringMVC中Json數(shù)據(jù)格式轉(zhuǎn)換的相關(guān)知識(shí)。具有很好的參考價(jià)值。下面跟著小編一起來看下吧2017-03-03Java調(diào)用DOS實(shí)現(xiàn)定時(shí)關(guān)機(jī)的實(shí)例
Java調(diào)用DOS實(shí)現(xiàn)定時(shí)關(guān)機(jī)的實(shí)例,需要的朋友可以參考一下2013-04-04詳解mybatis.generator配上最新的mysql 8.0.11的一些坑
這篇文章主要介紹了詳解mybatis.generator配上最新的mysql 8.0.11的一些坑,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-10-10Java使用Runnable和Callable實(shí)現(xiàn)多線程的區(qū)別詳解
這篇文章主要為大家詳細(xì)介紹了Java使用Runnable和Callable實(shí)現(xiàn)多線程的區(qū)別之處,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2022-07-07springboot解決java.lang.ArrayStoreException異常
這篇文章介紹了springboot解決java.lang.ArrayStoreException異常的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12