原生实现ajax封装
闲来无事封装了一下原生ajax请求本地mock数据
<script>
function ajax(options){
var xhr;
if(window.XMLHttpRequest){
// 考虑兼容性
xhr=new XMLHttpRequest();
}else if(window.ActiveObject){
// 兼容IE6以下版本
xhr=new ActiveXobject('Microsoft.XMLHTTP');
}
//启动并发送一个请求
if(options.type === "get"){
xhr.open("GET", options.url, true);
xhr.send(null);
}
// 接收
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
var status=xhr.status;
if(status>=200&& status<300 || status==304){
options.success && options.success(JSON.parse(xhr.responseText,xhr.responseXML));
}else{
options.error && options.error(status);
}
}
}
}
//基本的使用实例
ajax({
url:"./mock.json", // 相对路径
type:'get',
dataType:'json',
timeout:10000,
success:function(res){
console.log('res', res);
},
//异常处理
error:function(e){
console.log(e);
}
})
</script>
可以看到请求成功后的是本地mock的数据