Ajax
概述
Ajax是一种Web应用客户端技术,可以借助客户端脚本(javascript)与服务端应用进行异步通讯(可以有多个线程同时与服务器交互),并且按需获取服务端数据以后,可以进行局部刷新,进而提高数据的响应和渲染速度。
Ajax的优劣势
Ajax技术最大优势就是底层异步,然后局部刷新,进而提高用户体验。
Ajax可以仅像服务器发送并取回必要的数据,并在客户端采用JavaScript处理来自服务器的响应,这样在服务器和游览器之间交换的数据大量减少,服务器响应的熟读就更快了。
Ajax也有劣势,最大的劣势是不能直接进行跨域访问。
Ajax技术快速入门
Ajax请求响应模型
传统方式是web请求与响应(客户端要等待响应结果),如图:
Ajax方式的请求与响应(观建是客户端不阻塞),如图:
Ajax模板代码
第一步:基于dom事件创建XHR对象
let xhr=new XMLHttpRequest();
第二步:在XHR对象上注册状态监听(监听客户端与服务端的通讯过程)
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//表示服务端相应到客户端的数据已经接收完成
if(xhr.status==200){//表示服务端处理过程OK 500表示异常
console.log(xhr.responseText);
}
}
}
第三步:与服务端建立连接(指定请求方式,请求url,同步还是异步)
xhr.open("GET",URL,TRUE);
第四步:发送请求(将请求数据传递服务端)
xhr.send(null);
function doAjaxPost(){
//1.创建XHR对象
let xhr=new XMLHttpRequest();
//2.设置状态监听
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
let div=document.getElementById("result");
div.innerHTML=xhr.responseText;
}
}
}
//3.建立连接
let params="id=102&city=shenzhen"
xhr.open("post",`http://localhost/doAjaxPost`,true);
//post请求必须要设置请求头
xhr.setRequestHeader("Content-Type","application/x-www-formurlencoded");
//4.发送请求
xhr.send(params);//post请求可以将参数放到send方法内部
}
function doAjaxPostJson(){
//1.创建XHR对象
let xhr=new XMLHttpRequest();
//2.设置状态监听
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
let div=document.getElementById("result");
div.innerHTML=xhr.responseText;
}
}
}
Ajax Delete请求方式关键代码如下:
Ajax Put请求方式,关键代码如下:
//3.建立连接
let params={id:103,city:"xiongan"}
let paramsStr=JSON.stringify(params);//将json对象转换为json字符串
console.log("jsonStr",paramsStr);
xhr.open("post",`http://localhost/doAjaxPostJSON`,true);
//post请求必须要设置请求头
xhr.setRequestHeader("Content-Type","application/json");
//4.发送请求
xhr.send(paramsStr);//post请求可以将参数放到send方法内部
}
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编程框架的简易实现
(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-formurlencoded");
//发送请求
xhr.send(params);//post请求send方法中传递参数
}
}
window.Ajax=new ajax();//构建ajax对象并赋值给变量全局变量Ajax
})()
JQuery框架中Ajax技术的应用
常用Ajax函数分析
JQuery中基于标准的Ajax API提供了丰富的Ajax函数应用,基于这些函数可以编写少量代码,便可以快速实现Ajax操作。常用函数有:
ajax(…)
get(…)
getJSON(…)
post(…)
…
相关函数可参考官网(jquery.com)
ajax函数
<script>
function doAjax(){
let requestUrl="/doAjaxGet";
let params="";
//$符号在这里代表jquery对象
//ajax({})为jquery种的一个ajax函数,底层封装了ajax请求过程
$.ajax({
url:requestUrl,//key必须为url
data:params,
//type:"GET",//可以省略,默认为Get请求
dataType:"text",//服务端响应到客户端的数据格式,默认为json
//async:true,//默认异步
//contentType:"application/json",//假如需要向服务端传递json串
success:function(result){//callback 回调函数
console.log("result",result);
//JS原生写法
//document.querySelector("#result").innerHTML=result;
//Jquery种的封装简化写法
$("#result").html(result);
}
});
//假如服务端响应到客户端的数据为json格式字符串,底层会默认将其转换为json对象
}
</script>
get函数
function doGet(){
let requestUrl="/doAjaxGet";
let params="";
$.get(requestUrl,params,function(result){
$("#result").html(result);
},"text");//默认为json
}
post函数
function doPost(){
let requestUrl="/doAjaxPost";
let params="id=104&city=shijiazhuang";
$.post(requestUrl,params,function(result){
alert(result);
})
}
load函数
function doLoad(){
let requestUrl="/doAjaxGet";
//load函数会在指定位置通过ajax方法加载数据,并将数据更新到这个位置
$("#result").load(requestUrl,function(){//可选
console.log("==load complete==");//加载完成以后执行
});
}