ajaxシンプルパッケージ
function ajax(options) {
let defaults = {
type: 'get',
url: '',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
},
success: function() {
},
error: function() {
}
}
Object.assign(defaults, options);
const xhr = new XMLHttpRequest();
let params = '';
for (const key in defaults.data) {
params += key + '=' + defaults.data[key] + '&';
}
params = params.substring(0, params.length - 1);
if (defaults.type === 'get') {
defaults.url = defaults.url + '?' + params;
}
xhr.open(defaults.type, defaults.url);
if (defaults.type === 'post') {
let contentType = defaults.header['Content-Type'];
xhr.setRequestHeader('Content-Type', contentType);
if (contentType === 'application/json') {
xhr.send(JSON.stringify(defaults.data));
} else {
xhr.send(params);
}
} else {
xhr.send();
}
xhr.onload = function() {
const contentType = xhr.getResponseHeader('Content-Type');
let responseText = xhr.responseText;
if (contentType.includes('application/json')) {
responseText = JSON.parse(responseText);
}
if (xhr.status === 200) {
defaults.success(responseText, xhr);
} else {
defaults.error(responseText, xhr);
}
}
xhr.onerror = function(err) {
console.log(err);
}
}