Ajax是基于 XMLHttpRequest实现的
function ajax(options) {
let params = {
url: '',
type: 'get',
data: {},
sucess: function(data) {},
error: function(err) {}
}
options = Object.assign(params,options);
if (options.url) {
const xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
let url = options.url,
type = options.type.toUpperCase(),
data = options.data,
dataArr = [];
for (let key in data) {
let value = key + '=' + data[key];
dataArr.push(value);
}
if (type === 'GET') {
url = url + '?' + dataArr.join('&');
xhr.open(type,url,true);
xhr.send();
}
if (type === 'POST') {
xhr.open(type,url,true);
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send(dataArr.join('&'));
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && (xhr.state === 200 || xhr.state === 304)) {
options.success(xhr.responseText);
} else {
options.error(xhr.responseText);
}
}
}
}
其中,xhr.open(type, url, true)中的第三个参数意义如下:
当为 true 时,表示Javascript 异步执行,不等后台返回结果,直接执行后续操作;
当为 false 时,表示同步执行,等到后台结果返回后,再继续;