【原生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);
});