Ajax&Axios

Ajax

概念

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

作用

  • 與服務器進行數(shù)據(jù)交換:通過AJAX可以給服務器發(fā)送請求,并獲取服務器響應的數(shù)據(jù)
  • 后臺發(fā)送:瀏覽器的請求是后臺js發(fā)送給服務器的,js會創(chuàng)建單獨的線程發(fā)送異步請求,這個線程不會影響瀏覽器的線程運行
  • 局部刷新:瀏覽器接收到結果以后進行頁面局部刷新

未使用Ajax和使用Ajax后對比

  • 沒學習AJAX之前發(fā)送請求和獲取響應的方式
image-20221106155023762.png
- 瀏覽器發(fā)送HTTP返回的是一個完整的網(wǎng)頁,瀏覽器會顯示這個網(wǎng)頁
- 瀏覽器會等待服務器的響應(同步請求)
  • 學習AJAX之后
image-20221106155200255.png
  • AJAX返回的是部分數(shù)據(jù),瀏覽器內容不會變化
  • 后臺發(fā)送,不影響瀏覽器的操作(異步請求)

例子

使用了AJAX和服務器進行通信,就可以使用 HTML+AJAX來替換JSP頁面了

  • 使用HTTP獲取一個完整的網(wǎng)頁
image-20221106155358377.png
  • 登錄的時候輸入用戶名,失去焦點的時候,就會使用AJAX發(fā)送一個異步請求到后臺,然后返回用戶存在與否的結果
image-20221106155433408.png

Ajax原生API

  • 創(chuàng)建 XMLHttpRequest 對象:用于和服務器交換數(shù)據(jù)
let xmlhttp = new XMLHttpRequest()
  • 設置狀態(tài)回調監(jiān)聽,獲取服務器響應數(shù)據(jù)
xmlHttp.onreadystatechange=function (){
    if(xmlHttp.readyState==4 && xmlHttp.status=200){
        alert(xmlHttp.responseText);
    }
}
  • 發(fā)送請求
//設置請求方式和資源地址
xmlhttp.open("GET",“url");
//發(fā)送請求
xmlhttp.send();
  • API簡介
屬性 描述
onreadystatechange 定義了當 readyState 屬性發(fā)生改變時所調用的函數(shù)。
readyState 保存了 XMLHttpRequest 的狀態(tài)。
0: 請求未初始化
1: 服務器連接已建立
2: 請求已接收
3: 正在處理請求
4: 請求已完成且響應已就緒
status 200: "OK"
403: "Forbidden"
404: "Page not found"
statusText 返回狀態(tài)文本(例如 "OK" 或 "Not Found")

Ajax快速入門

學習網(wǎng)站:https://www.w3school.com.cn/

步驟

  • 編寫AjaxServlet,并使用response輸出字符串
/**
 * Ajax 異步的JavaScript和XML
 */
@WebServlet(value = "/ajaxServlet")
public class AjaxServlet extends HttpServlet {
    private static final long serialVersionUID = -2594113160049777689L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("hello ajax");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
  • 編寫HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax快速入門</title>
</head>
<body>
<script>
    //創(chuàng)建Ajax的核心對象
    let xmlHttpRequest = new XMLHttpRequest();
    //設置監(jiān)聽,獲取請求的響應數(shù)據(jù)(onreadystatechange 就是在狀態(tài)變化時進行回調)
    xmlHttpRequest.onreadystatechange = function () {
        //readyState == 4 表示請求完成,并且可以返回了響應數(shù)據(jù)到瀏覽器
        //status == 200 表示響應碼,200為請求成功,就可以獲取響應數(shù)據(jù)
        if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
            alert(xmlHttpRequest.responseText);
        }
    }
    //請求方式和URL的配置,并發(fā)送請求
    xmlHttpRequest.open('GET', "ajaxServlet");
    xmlHttpRequest.send();
</script>
</body>
</html>

Axios異步框架

注意:axios會自動將字符串truefalse轉換為boolean類型

Axios快速入門

步驟:

  • 編寫AxiosServlet,接收請求參數(shù),并使用response輸出字符串
@WebServlet(value = "/axiosServlet")
public class AxiosServlet extends HttpServlet {
    private static final long serialVersionUID = 7336379928784176967L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("接收到axios的請求:" + username + "=" + password);
        response.getWriter().write("hello " + username);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
  • 下載并引入axios的js文件
<script src="js/axios-0.18.0.js"></script>
  • 發(fā)送GET請求
axios({
    method: "GET",
    url: "axiosServlet?username=zhangsan&password=333"
}).then(resp => {
    //resp 表示響應對象,resp.data,表示響應數(shù)據(jù)
    alert(resp.data)
});
  • 發(fā)送POST請求
axios({
    method: "POST",
    url: "axiosServlet",
    data: "username=lisi&password=444"
}).then(resp => {
    alert(resp.data)
});
  • 編寫HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Axios快速入門</title>
    <script src="js/axios-0.18.0.js"></script>
</head>
<body>
<button onclick="testGet()">GET請求</button>
<button onclick="testPost()">Post請求</button>
<script>
    //使用Axios的GET請求
    function testGet() {
        axios({
            method: "GET",
            url: "axiosServlet?username=zhangsan&password=333"
        }).then(resp => {
            //resp 表示響應對象,resp.data,表示響應數(shù)據(jù)
            alert(resp.data)
        });
    }

    //使用Axios的POST請求
    function testPost() {
        axios({
            method: "POST",
            url: "axiosServlet",
            data: "username=lisi&password=444"
        }).then(resp => {
            alert(resp.data)
        });
    }
</script>
</body>
</html>

Axios 請求方式別名

  • 為了方便起見, Axios 已經為所有支持的請求方法提供了別名
axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])
  • 常用的別名
方法名 作用
get(url) 發(fā)起GET方式請求
post(url,請求參數(shù)) 發(fā)起POST方式請求
  • 發(fā)送GET請求
axios.get("axiosServlet?username=zhangsan&password=333")
.then(resp => {
    //resp.data 代表響應的數(shù)據(jù)
    alert(resp.data)
});
  • 發(fā)送POST請求
axios.post("axiosServlet", "username=wangwu&password=555")
.then(resp => {
    alert(resp.data)
});
  • 編寫HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Axios別名</title>
    <script src="js/axios-0.18.0.js"></script>
</head>
<body>
<button onclick="testGet()">GET請求</button>
<button onclick="testPost()">Post請求</button>
<script>
    //使用Axios的別名,進行GET請求
    function testGet() {
        //參數(shù):請求路徑和請求參數(shù)(存放在請求行)
        axios.get("axiosServlet?username=zhangsan&password=333")
            .then(resp => {
                //resp.data 代表響應的數(shù)據(jù)
                alert(resp.data)
            });
    }

    //使用Axios的別名方式,進行POST請求
    function testPost() {
        //第一個參數(shù):請求路徑(存放在請求行)
        //第二個參數(shù):請求參數(shù)(存放在請求體)
        axios.post("axiosServlet", "username=wangwu&password=555")
            .then(resp => {
                alert(resp.data)
            });
    }
</script>
</body>
</html>
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容