【原生ajax封装】

function ajaxPost(url, data, header, callback) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
for(let i in header){
xhr.setRequestHeader(i,header[i]);
}
xhr.send(JSON.stringify(data));
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
}
}

var url = ''
var data = {}
var callback = (resp)=>{

}
ajaxPost(url,data,null,callback);

//========================================================================================

function ajaxGet(url, callback) {
var xhr = new XMLHttpRequest(); xhr.open('GET', url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
}
}
// 调用
var url = ''

ajaxGet('url', function (data) {
console.log(data);
});

posted @ 2022-01-07 10:54  自律のalive  阅读(47)  评论(0编辑  收藏  举报