Web数据交互方式,Ajax:
Ajax,Asynchronous Javascript And XML(异步JavaScript和XML),2005年被Jesse James Garrett提出的新术语,用来描述一种使用现有技术集合的新方法,包括:HTML或XHTML,CSS,JavaScript,DOM,XML,XSLT,以及最重要的XMLHttpRequest。 使用Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,而不需要重载(刷新)整个页面,这使得程序能够更快地回应用户的操作。
jQuery
jQuery是一个快速、简洁的JavaScript框架,是继Prototype之后又一个优秀的JavaScript代码库(框架)于2006年1月由John Resig发布。封装了JavaScript常用的功能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作、事件处理、动画设计和Ajax交互。
Axios
一个基于promise的HTTP库,可以用在浏览器和node.js中。
跨域资源共享(CORS)
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
原生的Ajax同步&异步代码案例
//Ajax Get 同步请求function AjaxSynGet(url) { var xmlHttp; if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { //IE xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } // xmlHttp.setRequestHeader("headName", "headName"); xmlHttp.open("GET", url + '&rnd=' + Math.random(), false); xmlHttp.setRequestHeader("token","header-token-value"); xmlHttp.send(null); var text = xmlHttp.responseText; return text;}//Ajax Post 同步请求function AjaxSynPost(url, param) { var xmlHttp; if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { //IE xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttp.open("POST", url + '&rnd=' + Math.random(), false); xmlHttp.setRequestHeader("token","header-token-value"); xmlHttp.setRequestHeader("headName", 'headValue'); xmlHttp.send(param); var text = xmlHttp.responseText; return text;}//Ajax Get 异步请求// rtnFun: 函数function AjaxGet(url, rtnFun) { var xmlHttp; if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { //IE xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlHttp != null) { //get xmlHttp.open("GET", url + '&rnd=' + Math.random(), true); xmlHttp.setRequestHeader("token","header-token-value"); xmlHttp.send(null); xmlHttp.onreadystatechange = function() { //4 = "loaded" if (xmlHttp.readyState == 4) { //200 = OK if (xmlHttp.status == 200) { var text = xmlHttp.responseText; rtnFun(text); } } } }}//Ajax Post 异步请求// rtnFun: 函数function AjaxPost(url, param, rtnFun) { var xmlHttp; if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); //IE } else if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } if (xmlHttp != null) { xmlHttp.open("POST", url + '&rnd=' + Math.random(), true); xmlHttp.setRequestHeader("token","header-token-value"); xmlHttp.setRequestHeader("headName", 'headValue'); xmlHttp.send(param); xmlHttp.onreadystatechange = function() { //4 = "loaded" if (xmlHttp.readyState == 4) { //200 = OK if (xmlHttp.status == 200) { var text = xmlHttp.responseText; rtnFun(text); } } } }}
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>原生的Ajax同步&异步代码案例</title> <!--r为参数防止浏览器缓存 --> <script type="text/javascript" src="ajax.js?r=2"></script></head><body> <div> <span id="result1"></span> <hr/> <span id="result2"></span> <hr/> <span id="result3"></span> <hr/> <span id="result4"></span> </div> <script type="text/javascript"> // 1、Ajax Get同步请求 let result1 = AjaxSynGet("http://192.168.1.116:8080/data/get?a=1"); console.log("result1",result1); document.getElementById("result1").innerText=result1; // 2、Ajax Post 同步请求 let result2 = AjaxSynPost("http://192.168.1.116:8080/data/post?a=1","key=value"); console.log("result2",result2); document.getElementById("result2").innerText=result2; // 3、Ajax Get 异步请求 console.log("请求前:" + new Date().getTime()); AjaxGet("http://192.168.1.116:8080/data/get?a=1", function(data){ console.log("result3",data); document.getElementById("result3").innerText=data; }); console.log("请求后:" + new Date().getTime()); // 4、Ajax Ajax Post 异步请求 console.log("请求前:" + new Date().getTime()); AjaxPost("http://192.168.1.116:8080/data/post?a=1", "key=value", function(data){ console.log("result4",data); document.getElementById("result4").innerText=data; }); console.log("请求后:" + new Date().getTime()); </script></body></html>
jQuery的Ajax同步&异步代码案例
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>jQuery的Ajax同步&异步代码案例</title> <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js"></script></head><body> <div> <span id="result1"></span> <hr/> <span id="result2"></span> <hr/> <span id="result31"></span> <hr/> <span id="result32"></span> <hr/> <span id="result41"></span> <hr/> <span id="result42"></span> </div> <script type="text/javascript"> // 1、Ajax Get同步请求 let result1 = $.ajax({ type: 'get', url: 'http://192.168.1.116:8080/data/get', async:false, headers:{'token':'1333333333'}, }); console.log("result1",result1.responseText); $("#result1").text(result1.responseText); // 2、Ajax Post 同步请求 let result2 = $.ajax({ type: 'post', url: 'http://192.168.1.116:8080/data/post', data: {}, async:false, headers:{'token':'1333333333'}, }); console.log("result2",result2.responseText); $("#result2").text(result2.responseText); // 3、Ajax Get 异步请求 $.get("http://192.168.1.116:8080/data/get", function(data,status){ console.log("result31", JSON.stringify(data)); $("#result31").text(JSON.stringify(data)); }); $.ajax({ type: 'get', url: 'http://192.168.1.116:8080/data/get', async: true, headers:{'token':'1333333333'}, success: function (res){ console.log("result32", JSON.stringify(res)); $("#result32").text(JSON.stringify(res)); }, error:function(err){ console.log("error32", err); } }); // 4、Ajax AjaxPost 异步请求 $.post("http://192.168.1.116:8080/data/post",{ id:''},function(data){ console.log("result41", JSON.stringify(data)); $("#result41").text(JSON.stringify(data)); }); $.ajax({ type: 'post', url: 'http://192.168.1.116:8080/data/post', data:{ id:'' }, contentType: 'application/x-www-form-urlencoded', async: false, headers:{'token':'1333333333'}, success: function (res){ console.log("result42", JSON.stringify(res)); $("#result42").text(JSON.stringify(res)); }, error:function(err){ console.log("error42", err); } }); </script></body></html>
Axios的Ajax同步&异步代码案例
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title>Axios的Ajax同步&异步代码案例</title> <script src="https://lib.baomitu.com/axios/0.21.4/axios.min.js"></script> </head><body> <div> <span id="result11"></span> <hr/> <span id="result12"></span> <hr/> <span id="result21"></span> <hr/> <span id="result22"></span> <hr/> <span id="result31"></span> </div> <script type="text/javascript"> // URL编码 URL解码 console.log("URL编码",encodeURIComponent("名字")); console.log("URL解码",decodeURIComponent("%E5%90%8D%E5%AD%97")); // 1、Ajax Get异步请求 axios.get('http://192.168.1.116:8080/data/get?id=11&name=名字',{ params: {desc:"描述"}, headers: {"token": "token123"} }).then(res => { console.log("result11", JSON.stringify(res.data)); document.getElementById("result11").innerText = JSON.stringify(res.data); }); // 另外一种写法 axios({ url: 'http://192.168.1.116:8080/data/get?id=12&name=名字', method: 'GET', params: {desc:"描述"}, headers: {"token": "token123"} }).then(res => { console.log("result12", JSON.stringify(res.data)); document.getElementById("result12").innerText = JSON.stringify(res.data); }) // 2、Ajax Post异步请求 axios.post('http://192.168.1.116:8080/data/post',"id=21&name=名字",{ headers: {"token": "token123"} }).then(res => { console.log("result21", JSON.stringify(res.data)); document.getElementById("result21").innerText = JSON.stringify(res.data); }) // 另外一种写法 axios({ url: 'http://192.168.1.116:8080/data/post', method: 'post', data: {id: 22,name:'名字'}, headers: {"token": "token123"} }).then(res => { console.log("result22", JSON.stringify(res.data)); document.getElementById("result22").innerText = JSON.stringify(res.data); }); // 3、Ajax Get同步请求 console.log("请求前:" + new Date().getTime()); async function getData() { let data = ""; await axios.get('http://192.168.1.116:8080/data/get?id=31&name=名字').then(res => { data = JSON.stringify(res.data); console.log("执行1:" + new Date().getTime()); }); console.log("执行2:" + new Date().getTime()); return data; } const result = getData(); result.then(res=>{ console.log("执行3:" + new Date().getTime()); console.log("result31", res); document.getElementById("result31").innerText = res; }) console.log("请求后:" + new Date().getTime()); </script></body></html>
SpringBoot后台代码
跨域的Filter:
import javax.servlet.*;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD"); response.setHeader("Access-Control-Max-Age", "3600"); //response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With"); response.setHeader("Access-Control-Allow-Headers", "*"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {}}
配置(主要是跨域):
import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;@Configurationpublic class CommonConfig { @Bean public FilterRegistrationBean registerAuthFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new SimpleCORSFilter()); registration.addUrlPatterns("/*"); registration.setName("simpleCORSFilter"); registration.setOrder(1); // 值越小,Filter越靠前。 return registration; } private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); //允许任何域名 corsConfiguration.addAllowedHeader("*"); //允许任何头 corsConfiguration.addAllowedMethod("*"); //允许任何方法 return corsConfiguration; } // @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); //注册 return new CorsFilter(source); }}
Controller支持:
import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import javax.servlet.http.HttpServletRequest;import java.util.HashMap;import java.util.Map;import java.util.Random;@Controller@RequestMapping("/data")public class DataController { @RequestMapping(value = "/get", method = RequestMethod.GET) @ResponseBody public Object get(HttpServletRequest request) { Map<String, Object> dataMap = new HashMap<>(); dataMap.put("id", new Random().nextInt()); dataMap.put("name", "富豪"); dataMap.put("type", "GET"); return dataMap; } @RequestMapping(value = "/post", method = RequestMethod.POST) @ResponseBody public Object post(HttpServletRequest request) { Map<String, Object> dataMap = new HashMap<>(); dataMap.put("id", new Random().nextInt()); dataMap.put("name", "富豪"); dataMap.put("type", "POST"); return dataMap; }}