关于ajax:SpringBootAjax的使用

4次阅读

共计 8523 个字符,预计需要花费 22 分钟才能阅读完成。

Ajax 概述

Ajax 是什么?

Ajax (Asynchronous JavaScript and XML) 是一种 Web 利用客户端技术, 能够借助客户端脚本 (javascript) 与服务端利用进行异步通信(能够有多个线程同时与服务器交互),并且按需获取服务端数据当前, 能够进行部分刷新, 进而进步数据的响应和渲染速度。

Ajax 利用场景?

Ajax 技术最大的劣势就是底层异步, 而后部分刷新, 进而进步用户体验, 这种技术当初在很多我的项目中都有很好的利用, 例如:

  • 商品零碎。
  • 评估零碎。
  • 地图零碎。
  • …..

AJAX 能够仅向服务器发送并取回必要的数据,并在客户端采纳 JavaScript 解决来自服务器的响应。这样在服务器和浏览器之间替换的数据大量缩小,服务器响应的速度就更快了。但 Ajax 技术也有劣势,最大劣势是不能间接进行跨域拜访。

Ajax 申请响应过程剖析

传统形式是 web 申请与响应(客户端要期待响应后果), 如图所示:

Ajax 形式的申请与响应(要害是客户端不阻塞), 如图所示:

Ajax 编程步骤及模板代码剖析

Ajax 编码的根本步骤?(重点是 ajax 技术的入口 -XMLHttpRequest-XHR 对象)

第一步: 基于 dom 事件创立 XHR 对象
第二步: 在 XHR 对象上注册状态监听 (监听客户端与服务端的通信过程)
第三步: 与服务端建设连贯 (指定申请形式, 申请 url, 同步还是异步)
第四步: 发送申请(将申请数据传递服务端)

Ajax 编码过程的模板代码如下:

var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){if(xhr.readyState==4&&xhr.status==200){console.log(xhr.responseText)
    }
}
xhr.open("GET",url,true);
xhr.send(null);

SpringBoot 我的项目 Ajax 的利用

第一步:创立我的项目 13-springbooit-ajax


第二步: 增加 Spring web 依赖, 代码如下:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

第三步: 创立 AjaxController 解决客户端申请, 代码如下:

package com.cy.pj.ajax.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AjaxController {@RequestMapping("/doAjaxStart")
    public String doAjaxStart(){return "Response Result Of Ajax Get Request 01";}
}

第四步: 在我的项目中 static 目录下, 创立一个页面 ajax-01.html, 代码如下:

html 元素代码如下:

<h1>The Ajax 01 Page</h1>
<fieldset>
   <legend>Ajax 异步 Get 申请 </legend>
   <button onclick="doAjaxStart()">Ajax Get Request</button>
   <span id="result">Data is Loading ...</span>
</fieldset>

javascript 脚本代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Title</title>
</head>
<body>
    <div>
         <h1>The Ajax 01 Page</h1>
         <fieldset> <legend>Ajax 异步申请 </legend>
         <button onclick="doAjaxGet()">Ajax Get Request</button>
         <span id="resultId">Loading data....</span>
         </fieldset>
     </div>
</body>
<script>
     function doAjaxGet() {
                debugger;
         //1,创立 XHR 对象(此对象是 ajax 技术利用的入口对象,发送异步申请,解决响应后果都是通过此对象实现)
         var xhr = new XMLHttpRequest();
         //2,设置状态监听
         xhr.onreadystatechange = function () {// 工夫监听函数(解决客户端与服务端通过过程中产生的数据)//readyState 的值 0,1,2,3,4
         // 0 示意还未执行 open 办法
         // 1 示意已执行 open 办法但未执行 send 办法
         // 2 示意已执行 send 办法
         // 3 示意客户端正在承受服务端响应的数据
         // 4 示意客户端曾经实现响应数据的接管
         //200 示意服务端的处理过程是 ok 的
         if (xhr.readyState == 4 && xhr.status == 200) {
            var result = xhr.responseText;// 获取服务端响应的文本数据
            document.getElementById("resultId").innerHTML = result;
         }
                }
                //3,建设与服务端的连贯
         xhr.open("GET", "http://localhost/doAjaxGet", true);//true 示意异步申请
         //4,发送申请
         xhr.send(null);// 将申请交给 ajax 引擎
            console.log("do other...");
     }
</script>
</html>

第五步: 启动 Tomcat 服务并进行拜访测试剖析

ajax-02.html
post 和 get 的应用:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<div>
 <h1>The Ajax 02 Page</h1>
 <fieldset> <legend>Ajax 表单申请 </legend>
 <form> <input type="text" name="name" id="nameId" class="mingzi" onblur="doCheck()"/>
 <button type="button" onclick="doSave()">Save</button>
 </form> <span id="result"></span>
 </fieldset></div>
<script>
 function doSave(){// 发送异步申请, 查看 name 是否存在
 //1. 创立 xhr 对象(Ajax 技术利用的入口)
 let xhr=new XMLHttpRequest();
 //2. 设置状态监听(不是必须的, 然而如果要获取服务端响应的后果并进行解决就要进行状态监听)
 xhr.onreadystatechange=function(){if(xhr.readyState==4&&xhr.status==200){document.getElementById("result").innerHTML=xhr.responseText;
 }
        }
        //3. 建设 Get 连贯(get 申请传参数, 要将参数拼接到 url 中)
 let name=document.forms[0].name.value;// 获取表单中 name 对应的 value 属性值
 console.log("name",name);
 let url="http://localhost/doSave";
 xhr.open("POST",url,true);
 //post 申请如果须要向服务端传递参数, 则必须在 open 之后设置申请头
 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
 //4. 发送异步 POST 申请(参数须要写到 send 办法外部)- 表单数据或数据量比拟大时
 xhr.send(`name=${name}`);// 通过模板字符串 `` 和 ${}示意拼接 url}
    function doCheck(){// 发送异步申请, 查看 name 是否存在
 //1. 创立 xhr 对象
 debugger;
 var xhr = new XMLHttpRequest();
 //2,设置状态监听
 xhr.onreadystatechange = function () {if (xhr.readyState == 4 && xhr.status == 200) {
                var result = xhr.responseText;
 document.getElementById("result").innerHTML = result;
 }
        }
        //3,建设与服务端的连贯 Get(get 申请传参,要将参数拼接到 URl 中)
 let name=document.forms[0].name.value;// 获取表单中 name 对应的 value 属性值
 //let name=document.getElementById("nameId").value;// 基于节点 id 获取
 //let name=document.querySelector("#nameId").value;// 基于 id 选择器(前缀 "#")
 //let name=document.querySelector(".mingzi").value;// 基于 class 选择器(前缀 ".")
 //let name=document.querySelector("input").value; let url=`http://localhost:1314/doCheck?name=${name}`;// 通过模板字符串 `` 和 ${}拼接 url
 xhr.open("GET",url, true);
 //xhr.open("GET", "http://localhost/doCheck?name="+name, true);
 //4,发送申请
 xhr.send(null);// 将申请交给 ajax 引擎
 }
</script>
</body>
</html>

ajax-03.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<div>
 <h1>The Ajax 03 Page</h1>
 <fieldset> <legend>Ajax 表单申请 </legend>
 <form> <input type="text" name="name" id="nameId" class="mingzi" onblur="doCheck()"/>
 <button type="button" onclick="doSave()">Save</button>
 </form> <span id="result"></span>
 </fieldset></div>
<script>
 function doAjaxGet(url,params,callback){
            //1. 创立 xhr 对象
             debugger;
             var xhr = new XMLHttpRequest();
             //2,设置状态监听
             xhr.onreadystatechange = function () {if (xhr.readyState == 4 && xhr.status == 200) {
                var result = xhr.responseText;
 document.getElementById("result").innerHTML = result;
 }
        }
        //3,建设与服务端的连贯 Get(get 申请传参,要将参数拼接到 URl 中)
         xhr.open("GET",`${url}?${params}`, true);
         //4,发送申请
         xhr.send(null);// 将申请交给 ajax 引擎
         }
    function doAjaxPost(url,params,callback) {//1. 创立 xhr 对象(Ajax 技术利用的入口)
         let xhr = new XMLHttpRequest();
         //2. 设置状态监听(不是必须的, 然而如果要获取服务端响应的后果并进行解决就要进行状态监听)
         xhr.onreadystatechange = function (callback) {if (xhr.readyState == 4 && xhr.status == 200) {callback(xhr.responseText);
 }
        }
        //3. 建设 Get 连贯(get 申请传参数, 要将参数拼接到 url 中)
         xhr.open("POST", url, true);
         //post 申请如果须要向服务端传递参数, 则必须在 open 之后设置申请头
         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         //4. 发送异步 POST 申请(参数须要写到 send 办法外部)- 表单数据或数据量比拟大时
         xhr.send(`name=${params}`);// 通过模板字符串 `` 和 ${}示意拼接 url}
        function doSave() {// 发送异步申请, 查看 name 是否存在
         //1, 定义申请 url
         let url = "http://localhost:1314/doSave";
         let params = document.forms[0].name.value;// 获取表单中 name 对应的 value 属性值
         doAjaxPost(url, params, function (result) {document.getElementById("result").innerHTML = result;
         })
        }
        function doCheck() {// 发送异步申请, 查看 name 是否存在
         let name = document.forms[0].name.value;// 获取表单中 name 对应的 value 属性值
         let params = `name=${name}`;
         let url = `http://localhost:1314/doCheck`;// 通过模板字符串 `` 和 ${}拼接 url
         doAjaxGet(url, params, function (result) {document.getElementById("result").innerHTML = result;
         })
        }
</script>
</body>
</html>

axios-ajax-01.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<div>
 <button onclick="doAxiosAjaxGet()">axios.get(...)</button>
 <button onclick="doAxiosAjaxPost()">axios.post(...)</button>
 <button onclick="doAxiosAjaxPostJSON()">axios.postJSON(...)</button>
</div>
<div class="result"></div>
<script src="js/axios.min.js"></script>
<script>
 function doAxiosAjaxPostJSON(){
        //1,url
 let url="http://localhost/doPostJSON";
 //2,params
 let params={"msg":"hello axios"};
 //3,send axios ajax request
 axios.post(url,params)
            .then(function (result){//callback function
 document.querySelector(".result").innerHTML=JSON.stringify(result.data);// 原生的 JS 代码
 })
            .catch()}
    function doAxiosAjaxPost(){
        //1,url
 let url="http://localhost/doPost";
 //2,params
 let params="msg=hello axios";
 //3,send axios ajax request
 axios.post(url,params)
            .then(function (result){//callback function
 document.querySelector(".result").innerHTML=JSON.stringify(result.data);// 原生的 JS 代码
 })
            .catch()}
    function doAxiosAjaxGet(){
        //1,url
 let url="http://localhost/doAjax";
 //2,params
 let params={params: {"msg":"hello axios"}}
        //3,send ajax get request
 axios.get(url,params)
            .then(function (result){//callback function
 document.querySelector(".result").innerHTML=JSON.stringify(result.data);// 原生的 JS 代码
 })
            .catch()}
</script>
</body>
</html>

jquery-ajax-01.html

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Title</title>
</head>
<body>
    <div>
         <button onclick="doAxiosAjaxGet()">axios.get(...)          </button>
         <button onclick="doAxiosAjaxPost()">axios.post(...)</button>
         <button onclick="doAxiosAjaxPostJSON()">axios.postJSON(...)</button>
    </div>
    <div class="result"></div>
    <script src="js/axios.min.js"></script>
    <script>
        function doAxiosAjaxPostJSON(){
            //1,url
             let url="http://localhost/doPostJSON";
             //2,params
             let params={"msg":"hello axios"};
             //3,send axios ajax request
             axios.post(url,params)
            .then(function (result){//callback function
            document.querySelector(".result").innerHTML=JSON.stringify(result.data);// 原生的 JS 代码
 })
            .catch()}
    function doAxiosAjaxPost(){
        //1,url
             let url="http://localhost/doPost";
             //2,params
             let params="msg=hello axios";
             //3,send axios ajax request
             axios.post(url,params)
            .then(function (result){//callback function
 document.querySelector(".result").innerHTML=JSON.stringify(result.data);// 原生的 JS 代码
 })
            .catch()}
    function doAxiosAjaxGet(){
        //1,url
             let url="http://localhost/doAjax";
             //2,params
             let params={params: {"msg":"hello axios"}}
                    //3,send ajax get request
             axios.get(url,params)
            .then(function (result){//callback function
 document.querySelector(".result").innerHTML=JSON.stringify(result.data);// 原生的 JS 代码
 })
            .catch()}
</script>
</body>
</html>
正文完
 0