Ajax 技术简介
背景剖析?
在互联网高速倒退的明天,传统的WEB利用,对于高并发、高性能、高可靠性的要求已火烧眉毛。单线程形式的客户端与服务端交互方式曾经不能满足现阶段的需要.咱们须要以异步、按需加载的形式从服务端获取数据并及时刷新,来进步用户体验,于是Ajax技术诞生。
Ajax 是什么?
Ajax (Asynchronous JavaScript and XML) 是一种Web利用客户端技术,能够借助客户端脚本(javascript)与服务端利用进行异步通信(能够有多个线程同时与服务器交互),并且按需获取服务端数据当前,能够进行部分刷新,进而进步数据的响应和渲染速度。
Ajax 利用场景?
Ajax技术最大的劣势就是底层异步,而后部分刷新,进而进步用户体验,这种技术当初在很多我的项目中都有很好的利用,例如:
- 商品零碎。
- 评估零碎。
- 地图零碎。
- …..
AJAX能够仅向服务器发送并取回必要的数据,并在客户端采纳JavaScript解决来自服务器的响应。这样在服务器和浏览器之间替换的数据大量缩小,服务器响应的速度就更快了。但Ajax技术也有劣势,最大劣势是不能间接进行跨域拜访。
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技术入门实现
第一步:创立我的项目module,如图所示:
第二步:增加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;@RestControllerpublic 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 脚本代码如下:
function doAjaxStart(){ //debugger//客户端断点(此断点失效须要关上控制台) //1.创立XHR对象(XmlHttpRequest)-Ajax利用的入口对象 let xhr=new XMLHttpRequest(); //2.在XHR对象上注册状态监听(拿到服务端响应后果当前更新到页面result地位) xhr.onreadystatechange=function(){//事件处理函数(客户端与服务端通信状态发生变化 时会执行此函数) //readyState==4示意服务端响应到客户端数据曾经接管实现. if(xhr.readyState==4){ if(xhr.status==200){//status==200示意申请处理过程没问题 document.getElementById("result").innerHTML= xhr.responseText; } } } //3.与服务端建设连贯(指定申请形式,申请url,异步) xhr.open("GET","http://localhost/doAjaxStart",true);//true代表异步 //4.向服务端发送申请 xhr.send(null);//get申请send办法外部不传数据或者写一个null//如果是异步客户端执行完send会持续向下执行.}
第五步:启动Tomcat服务并进行拜访测试剖析.
点击Ajax Get Request 按钮,检测页面数据更新.
第六步:启动及拜访过程中的Bug剖析
- 点击按钮没反馈
- 拜访指定属性的对象不存在
- 跨域拜访
Ajax 根本业务实现
根本业务形容
基于对ajax技术了解,实现ajax形式的Get,Post,Put,Delete等申请的异步解决,如图所示:
服务端要害代码设计及实现
基于业务形容,在AjaxController类中增加相干属性和办法,用于解决客户端的ajax申请.
增加属性和构造方法,代码如下:
/**假如这个是用于存储数据的数据库*/ private List<Map<String,String>> dbList=new ArrayList<>(); public AjaxController(){ Map<String,String> map=new HashMap<String,String>(); map.put("id","100"); map.put("city","beijing"); dbList.add(map); map=new HashMap<String,String>(); map.put("id","101"); map.put("city","shanghai"); dbList.add(map); }
增加Ajax申请解决办法,代码如下:
@GetMapping(path={"/doAjaxGet/{city}","/doAjaxGet")public List<Map<String,String> doAjaxGet(@PathVariable(required=false) String city){ List<Map<String,String>> list=new ArrayList<>(); for(Map<String,String> map:dbList){ if(map.get("city").contains(city)){ list.add(map); } } return list;}@PostMapping("/doAjaxPost")public String doAjaxPost(@RequestParam Map<String,String> map){ dbList.add(map); return "save ok";}@PostMapping("/doAjaxPostJson")public String doAjaxPost(@RequestBody Map<String,String> map){ dbList.add(map); return "save ok";}@DeleteMapping("/doAjaxDelete/{id}")public String doDeleteObject(@PathVariable String id){ //基于迭代器执行删除操作 Iterator<Map<String,String>> it=dbList.iterator(); while(it.hasNext()){ Map<String,String> map=it.next(); if(map.get("id").equals(id)){ it.remove();//基于迭代器执行删除操作 } } return "delete ok";} @PostMapping("/doAjaxPut")public String doAjaxPut(@RequestParam Map<String,String> paramMap){ for(Map<String,String> map:dbList){ if(map.get("id").equals(paramsMap.get("id"))){ map.put("city",paramMap.get("city")) } } return "update ok";}
客户端要害代码设计及实现
在static目录下创立ajax-02.html文件,要害代码如下:
<div> <h1>The Ajax 02 Page</h1> <button onclick="doAjaxGet()">Do Ajax Get</button> <button onclick="doAjaxPost()">Do Ajax Post</button> <button onclick="doAjaxPostJson()">Do Ajax Post Json</button> <button onclick="doAjaxDelete()">Do Ajax Delete</button> <button onclick="doAjaxPut()">Do Ajax Put</button></div>
客户端JavaScript脚本设计,代码如下:
- Get 申请形式,代码如下:
function doAjaxGet(){ let xhr=new XMLHttpRequest(); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ document.getElementById("result").innerHTML=xhr.responseText; } } } let params="" xhr.open("GET",`http://localhost/doAjaxGet/${params}`,true); xhr.send(null); }
- Post 申请形式,代码如下:
function doAjaxPost(){ let xhr=new XMLHttpRequest(); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ document.getElementById("result").innerHTML=xhr.responseText; } } } xhr.open("POST","http://localhost/doAjaxPost",true); //post申请向服务端传递数据,须要设置申请头,必须在open之后 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //发送申请(post申请传递数据,须要将数据写入到send办法外部) xhr.send("id=102&city=shenzhen");}
function doAjaxPost(){ let xhr=new XMLHttpRequest(); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ document.getElementById("result").innerHTML=xhr.responseText; } } } xhr.open("POST","http://localhost/doAjaxPost",true); //post申请向服务端传递数据,须要设置申请头,必须在open之后 xhr.setRequestHeader("Content-Type", "application/json"); //发送申请(post申请传递数据,须要将数据写入到send办法外部) let params={id:103,city:"xiongan"}; let paramsStr=JSON.stringify(params); xhr.send(paramsStr);}
- Update 申请形式,代码如下:
function doAjaxPut(){ let xhr=new XMLHttpRequest(); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ document.getElementById("result").innerHTML=xhr.responseText; } } } xhr.open("put","http://localhost/doAjaxPut",true); //post申请向服务端传递数据,须要设置申请头,必须在open之后 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //发送申请(post申请传递数据,须要将数据写入到send办法外部) xhr.send("id=101&city=tianjin"); }
- Delete 申请形式,代码如下:
function doAjaxDelete(){ let xhr=new XMLHttpRequest(); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ document.getElementById("result").innerHTML=xhr.responseText; } } } let params="102"; xhr.open("delete",`http://localhost/doAjaxDelete/${params}`,true); xhr.send(null); }
启动服务进行拜访测试剖析
Ajax 技术进阶实现
Ajax 代码的封装
在理论编程过程中咱们通常会封装代码共性,提取代码个性.而后来进步代码的可重用性.例如:
xhr对象的创立
function createXHR(callback){ //1.create XHR object let xhr=new XMLHttpRequest(); //2.set onreadystatechange xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ callback(xhr.responseText); } } } return xhr;}
Get申请
function ajaxGet(url,params,callback){//封装ajax get 申请模板代码 //1.create xhr and set onreadystate change let xhr=createXHR(callback); //2.open connection xhr.open("GET",`${url}/${params}`,true); //3.send request xhr.send();}
Post申请
function ajaxPost(url,params,callback){//封装ajax get 申请模板代码 //1.create xhr and set onreadystate change let xhr=createXHR(callback); //2.open connection xhr.open("POST",url,true); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //3.send request xhr.send(params);}
post 申请,传递json数据
function ajaxPostJSON(url,params,callback){ //1.create xhr and set onreadystate change let xhr=createXHR(callback); //2.open connection xhr.open("POST",url,true); xhr.setRequestHeader("Content-Type","application/json"); //3.send request xhr.send(JSON.stringify(params));//将json对象转换为json格局字符串提交到服务端}
Put申请
function ajaxPut(url,params,callback){//封装ajax get 申请模板代码 //1.create xhr and set onreadystate change let xhr=createXHR(callback); //2.open connection xhr.open("put",url,true); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //3.send request xhr.send(params);}
delete申请
function ajaxDelete(url,params,callback){//封装ajax get 申请模板代码 //1.create xhr and set onreadystate change let xhr=createXHR(callback); //2.open connection xhr.open("delete",`${url}/${params}`,true); //3.send request xhr.send();}
创立ajax-03.html页面,在页面中别离调用如上函数进行拜访测试,要害代码如下:
<div> <h1>The Ajax 03 Page</h1> <button onclick="doAjaxGet()">Do Ajax Get</button> <button onclick="doAjaxPost()">Do Ajax Post</button> <button onclick="doAjaxPostJson()">Do Ajax Post Json</button> <button onclick="doAjaxDelete()">Do Ajax Delete</button> <button onclick="doAjaxPut()">Do Ajax Put</button> </div> <div id="result"></div> <script src="/js/ajax.js"></script> <script> //ajax delete request function doAjaxDelete(){ const url="/doAjaxDelete"; const params="101"; ajaxDelete(url,params,function(result){ alert(result); }) } //ajax post put function doAjaxPut(){ const url="/doAjaxPut"; const params="id=100&city=shenzhen"; ajaxPut(url,params,function(result){ alert(result); }) } //ajax post request function doAjaxPostJson(){ const url="/doAjaxPostJSON"; const params={id:"103",city:"xiongan"};//服务端须要@RequestBody ajaxPostJSON(url,params,function(result){ alert(result); }) } //ajax post request function doAjaxPost(){ const url="/doAjaxPost"; const params="id=102&city=shenzhen"; ajaxPost(url,params,function(result){ alert(result); }) } //ajax get request function doAjaxGet(){ const url="/doAjaxGet"; const params=""; ajaxGet(url,params,function(result){ document.querySelector("#result").innerHTML=result; }) } </script>
Ajax 编程小框架的实现(理解)
咱们在理论的js编程中常常会以面向对象的形式进行实现,例如ajaxGet函数,如何以对象形式进行调用呢?要害代码剖析如下:(如下代码的了解须要具备JS中面向对象的基础知识,如果不熟可临时跳过)
(function(){ //定义一个函数,能够将其连贯为java中的类 var ajax=function(){} //在变量ajax指向的类中增加成员,例如doAjaxGet函数,doAjaxPost函数 ajax.prototype={ ajaxGet:function(url,params,callback){ //创立XMLHttpRequest对象,基于此对象发送申请 var xhr=new XMLHttpRequest(); //设置状态监听(监听客户端与服务端通信的状态) xhr.onreadystatechange=function(){//回调函数,事件处理函数 if(xhr.readyState==4&&xhr.status==200){ //console.log(xhr.responseText); callback(xhr.responseText);//jsonStr } }; //建设连贯(申请形式为Get,申请url,异步还是同步-true示意异步) xhr.open("GET",url+"?"+params,true); //发送申请 xhr.send(null);//GET申请send办法不写内容 }, ajaxPost:function(url,params,callback){ //创立XMLHttpRequest对象,基于此对象发送申请 var xhr=new XMLHttpRequest(); //设置状态监听(监听客户端与服务端通信的状态) xhr.onreadystatechange=function(){//回调函数,事件处理函数 if(xhr.readyState==4&&xhr.status==200){ //console.log(xhr.responseText); callback(xhr.responseText);//jsonStr } }; //建设连贯(申请形式为POST,申请url,异步还是同步-true示意异步) xhr.open("POST",url,true); //post申请传参时必须设置此申请头 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //发送申请 xhr.send(params);//post申请send办法中传递参数 } } window.Ajax=new ajax();//构建ajax对象并赋值给变量全局变量Ajax})()
此时外界再调用doAjaxGet和doAjaxPost函数时,能够间接通过Ajax对象进行实现。
Ajax 技术在Jquery中的利用
Jquery简介
jQuery是一个疾速、简洁的JavaScript库框架,是一个优良的JavaScript代码库(或JavaScript框架)。jQuery设计的主旨是“write Less,Do More”,即提倡写更少的代码,做更多的事件。它封装JavaScript罕用的性能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作、事件处理、动画设计和Ajax交互。
Jquery中罕用ajax函数剖析
jQuery中基于规范的ajax api 提供了丰盛的Ajax函数利用,基于这些函数能够编写大量代码,便能够疾速实现Ajax操作。罕用函数有:
- ajax(…)
- get(…)
- getJSON(…)
- post(…)
- …
阐明:jquery 中ajax相干函数的语法可参考官网(jquery.com).
Jquery中Ajax函数的根本利用实现
业务形容
构建一个html页面,并通过一些button事件,演示jquery中相干ajax函数的根本利用,如图所示:
关键步骤及代码设计如下:
第一步:在static目录下增加jquery-ajax-01.html页面.
第二步:在页面上增加要害的html元素,代码如下:
<h1>The Jquery Ajax 01 Page</h1><button onclick="doAjax()">$.ajax(...)</button><button onclick="doAjaxPost()">$.post(...)</button><button onclick="doAjaxGet()">$.get(...)</button><button onclick="doAjaxLoad()">$("..").load(...)</button><div id="result"></div><script src="/js/jquery.min.js"></script>
第三步:增加button事件对应的事件处理函数,代码如下:
- ajax 函数利用,代码如下:
function doAjax(){ let url="http://localhost/doAjaxGet"; let params=""; //这里的$代表jquery对象 //ajax({})这是jquery对象中的一个ajax函数(封装了ajax操作的根本步骤) $.ajax({ type:"GET",//省略type,默认就是get申请 url:url, data:params, async:true,//默认为true,示意异步 success:function(result){//result为服务端响应的后果 console.log(result);//ajax函数外部将服务端返回的json串转换为了js对象 }//success函数会在服务端响应状态status==200,readyState==4的时候执行. });}
- post 函数利用,代码如下
function doAjaxPost(){ let url="http://localhost/doAjaxPost"; let params="id=101&name=Computer&remark=Computer..."; $.post(url,params,function(result){ $("#result").html(result);});
- get函数利用,代码如下:
function doAjaxGet(){ let url="http://localhost/doAjaxGet"; let params=""; $.get(url,params,function(result){ $("#result").html(result); },"text");}
- load 函数利用,代码如下:
function doAjaxLoad(){ let url="http://localhost/doAjaxGet"; $("#result").get(url,function(){ console.log("load complete") });}
总结(Summary)
本章次要介绍了Ajax是什么、利用场景、客户端与服务端的通信模型、ajax编程的根本步骤、封装过程以及ajax技术在一些JS框架中的利用等,并且重点剖析了在ajax编码过程中的一些调试技巧。
javascriptspringboot