ajax的出现直接推进了从以往的混合模式开发往前后端分离开发的转型,下面简单实现以下jquery中的ajax请求,加深对ajax的理解与运用。主要就$.ajax()、$.get()、$.post()作简单,使用立即执行函数,函数中返回对象作一个模块。
/**
*使用举例:
ajax请求:
xhr.ajax({
url:"http://localhost:3002/api",
type:"POST",
data:{
state:1,
},
success: data => {
console.log(data);
},
error: err => {
console.log(err);
},
complete: _ => {
}
})
get请求
xhr.get("http://localhost:3002/api",data=>{console.log(data)})
post请求:
xhr.post("http://localhost:3002/api",{state:1}, data=>{console.log(data)})
*/
var xhr = (function(){
function _doAjax(opt){
// 获取数据
var type = (opt.type || "GET").toUpperCase(),
url = opt.url,
async = opt.async || true, // 默认为异步
data = opt.data || null, //GET请求的数据为null
success = opt.success || function(){},
error = opt.error || function(){},
complete = opt.complete || function(){};
// 创建XMLHttpRequest对象
var o = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
if(!url){
throw new Error("你没有填写URL");
}else{
o.open(type, url, async);
if(type==="POST"){
// 设置请求头部的信息
o.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
data && (data = _formateData(data));
}
o.send(data); //发出请求
o.onreadystatechange = function(){
if(o.readyState === 4 && o.status === 200){
success(JSON.parse(o.responseText));
}
if(o.status === 404){
error();
}
complete();
}
}
}
// POST请求时将请求的对象数据data转换成&连接
function _formateData(data) {
var res = '';
for(var key in data){
res += key + "=" + data[key]+'&';
}
return res.replace(/&$/, '');
}
return {
ajax(opt){
_doAjax(opt);
},
get(url,cb){
_doAjax({
url,
success: cb,
});
},
post(url, data, cb){
_doAjax({
type:"POST",
url,
data,
success: cb,
});
}
}
})(); //立即执行函数,函数可作模块对象。