const $ = (function() {
return {
ajax: function({type,url,data,isAsync,success}) {
if (!url) {
console.error('请求地址为空')
return;
}
//创建 非IE6
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else { //IE6及其以下版本浏览器
var xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
// 处理data对象
var queryData = [];
for (var key in data) {
// 默认encodeURIComponent
queryData.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
queryData = queryData.join('&');
//连接 和 发送
if (!type || type == 'GET') {
// get方式参数要跟在url上
url = url + '?' + queryData;
xhr.open("GET", url, isAsync || true);
xhr.send(null);
}else if(type=='POST'){
xhr.open(type,url,isAsync || true);
//HTTP请求头赋值
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(queryData);
}
//接收
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// 有传入success回调就执行
success && success(xhr.responseText);
}
}
}
}
})();
//调用
$.ajax({
type: 'GET',
url: 'xxx',
data: {
type: 1
},
success: function(res) {
console.log(res);
}
})
$.ajax({
type: 'POST',
url: 'xxx',
data: {
type: 1
},
success: function(res) {
console.log(res);
}
})