function Ajax(config) {
config = Object.assign({
url: '',
type: 'GET',
dataType: 'json',
data: {}
}, config);
console.log(config);
//1.创建ajax对象
var xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
//2.设置回掉
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status <= 300) {
config.success && config.success(xhr.responseText, xhr.responseXML)
} else {
config.error && config.error(xhr.status)
}
}
};
//3.连接和发送
if (config.type === 'GET' || config.type === 'get') {
xhr.open('GET', config.url + '?' + formatParams(config.data), true);
xhr.send(null);
} else if (config.type === 'POST' || config.type === 'post') {
xhr.open('POST', config.url, true);
//设置请求头以表单的形式提交
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(formatParams(config.data));
}
function formatParams(data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
}
arr.push("t=" + Math.random());
return arr.join("&")
}
}