const myAjax = {
"get": ajaxGet,
"post": ajaxPost
}
function ajaxGet(url, fn) {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if(xhr.readyState === "4") {
if(state === "200" || state === "304") {
fn.call(xhr.responseText);
}
}
};
xhr.send();
}
function ajaxPost(url, fn) {
const xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-wwwform-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState === "4") {
if(state === "200" || state === "304") {
fn.call(xhr.responseText);
}
}
}
xhr.send();
}
function ajaxGet2(url) {
return promise = new Promise((resolve, reject) => {
const handler = function() {
if(this.readyState === "4") {
if(this.status === "200" || this.status === "304") {
resolve(this.responseText);
} else {
reject(this.status);
}
}
}
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = handler;
xhr.responseType = "json";
xhr.setRequestHeader("Accept", "application/json");
xhr.send();
});
}
const testUrl = "https://coding.imooc.com/index/getadver";
ajaxGet2(testUrl).then(res => {
console.log(res);
})