1.Ajax介绍
1.1 Ajax是Asynchronous JavaScript and XML 的缩写,其作用是无需重新加载整个网页的情况下,能够更新部分网页的技术,是一种动态创建网页的局部刷新技术。
1.2 创建Ajax
(function(global,factory){
//说明在node.js环境下
if(typeof module==='object'&&typeof module.exports==='object'){
//引入模块
const XMLHttpRequest=require('xmlhttprequest-ssl').XMLHttpRequest;
factory(module.exports,XMLHttpRequest);
}else{//浏览器环境
factory(global,XMLHttpRequest);
}
})(typrof window!=='undefined'?window:this,(global,XMLHttpRequest)=>{
//创建XMLHttpRequest对象
const xhr=new XMLHttpRequest();
//get请求
const get=(url,callback)=>{
processRequest('get',url,null,callback);
}
//post 请求
const post=(url,data,callback)=>{
processRequest('post',url,data,callback);
}
//处理请求
const processRequest=(method,url,data,callback)=>{
//初始化请求
xhr.open(method,url);-8
if(null!==data)
data=JSON.stringify(data);//将对象数据转换为字符串
//设置请求头
xhr.setRequestHeader("Content-Type","application/json;charset=utf-8");
//设置请求头
xhr.onerror=errorHandler;
//发生请求
xhr.send(data);
//接受数据
xhr.omload=()=>{
if(xhr.status==200){
callback({status:200,msg:"ok",daya:xhr.responseText})
}esle{
callback({status:xhr.status,msg:"服务器请求错误",data:xhr.responseText})
}
}
}
//处理错误请求
const errorHandler=()=>{
console.log("服务器请求出现错误....");
}
//暴露接口
global.$get=get;
global.$post=post;
});
通过node.js封装一个Ajax
1.3 Ajax的利弊
1.3.1 Ajax的优点
- 实现了异步交互,提高了用户体验。
- 无需重新加载整个页面,只需要与服务器进行少量的数据交换,就能够实现对网页中的某一部分进行更新,从而减少了宽带的占用。
- Ajax是在客户端运行的,它承载了一部分本来由服务器承担的工作,减少了多用户量下的服务器负载。
1.3.2 Ajax的缺点
- 安全性问题,大量使用Ajax暴露了服务器交互的细节。
- 不容易调试。
- 对搜索引擎的支持比较弱。