封装ajax函数

ajax函数,用来与后端的交互(请求类型有POST GET DELETE PUT HEAD,请求地址,callback请求的回调函数,参数,是否异步)

function ajax(method, url, callback, data, flag) {
 // xhr 用来存储请求与响应的信息
 var xhr = null;
if(window.XMLHttpRequest) {
 xhr = new XMLHttpRequest();
}else {
 xhr = new ActiveXObject('Microsoft.XMLHttp');
}
// // 监听数据请求状态 监听状态readyState的变化
xhr.onreadystatechange = function() {
// // 1 2 3
if(xhr.readyState == 4) {
// // 4xx url data
if(xhr.status == 200) {
 callback(xhr.responseText);
 }else {
 console.log('error');
 }
}
 }

/method = method.toUpperCase();
// // get 请求 把数据拼接在地址身上
if(method == 'GET') {
// // 建立连接
 xhr.open(method, url + '?' + data, flag);
// // 发出请求
 xhr.send();

// // post 请求需要把数据放在请求体里面 不拼接地址
 }else if(method == 'POST') {
// // 建立连接
xhr.open(method, url, flag);
// // 前端告诉后端 我的数据是什么格式的 key=value&key1=value1
 xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
// // 传递数据 发出请求i
 xhr.send(data);
// }
// }

 

posted @ 2019-07-14 00:24  不负好时光i  阅读(358)  评论(0编辑  收藏  举报