jQuery其实用的稀里糊涂的,原生JavaScript其实也很有趣的。搞一个原生的Ajax封装大概下午到晚上。参考了网上很多大佬的博客,坑坑中过来的。
$(function(){
//开始
function baseAjax(options){
options = options || {}; //默认对象;
options.method = (options.method || "GET").toUpperCase(); //默认为GET请求;
options.dataType = options.dataType || 'json'; //默认返回类型为JSON;
options.async = options.async || true; //默认为异步请求;
var params = getParams(options.data); //数据;
console.log('data: '+params);
var xhr = (window.XMLHttpRequest)? new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
var status = xhr.status;
if(status>=200 && status <300) //发送成功
options.success && options.success(xhr.responseText,xhr.responseXML);
else{ //执行成功;
options.fail && options.fail(status);
}
}
};
//数据发送;
if(options.method=='GET'){
xhr.open("GET",options.url+'?'+params,options.async);
xhr.send(null);
}else if(options.method=='POST'){
xhr.open('POST',options.url,options.async);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
console.log(params);
xhr.send(params);
}
};
function getParams(data){
var arr=[];
for(var param in data){
arr.push(encodeURIComponent(param)+'='+encodeURIComponent(data[param]));
}
//console.log(arr);
arr.push(('randomNumber='+Math.random()).replace('.'));
console.log(arr.join('&'));
return arr.join('&');
}
//函数调用:
document.getElementsByName('href')[0].onchange=function(){
var val={url:this.value}
baseAjax({
url:'cache.php', //地址
method:'POST', //请求方式
data: val, //发送数据;
dataType:'json', //返回类型;
async:true, //异步;
success:function(response,xml){ //请求成功的后代码;
console.log(response);
},
fail:function(status){ //执行成功后的代码;
console.log('成功状态代码: '+status);
}
});
}
//结束
});
翻了一些错,学到了一些东西:
1. 把baseAjax单词拼错,郁闷了一大会。
2. 参考别人的代码,把自己原本定义的method写成了type。导致后台一直接受不到数据;
3. 学会使用浏览器的调试工具!这是个惊喜。除错更快。
May 05,2018。今日音乐:《U Make Me WannaMV》 - Blue
;