2016-02-08 10:57:44 -05:00
|
|
|
AnimeClient = (function (ac) {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Url encoding for non-get requests
|
|
|
|
*
|
|
|
|
* @param data
|
|
|
|
* @returns {string}
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
function serialize(data) {
|
|
|
|
let pairs = [];
|
|
|
|
|
|
|
|
Object.keys(data).forEach((name) => {
|
|
|
|
let value = data[name].toString();
|
|
|
|
|
|
|
|
name = encodeURIComponent(name);
|
|
|
|
value = encodeURIComponent(value);
|
|
|
|
|
|
|
|
pairs.push(`${name}=${value}`);
|
|
|
|
});
|
|
|
|
|
|
|
|
return pairs.join("&");
|
|
|
|
};
|
|
|
|
|
|
|
|
ac.ajax = function(url, config) {
|
|
|
|
// Set some sane defaults
|
|
|
|
config = config || {};
|
|
|
|
config.data = config.data || {};
|
|
|
|
config.type = config.type || 'GET';
|
2016-02-08 13:37:44 -05:00
|
|
|
config.dataType = config.dataType || '';
|
2016-02-08 10:57:44 -05:00
|
|
|
config.success = config.success || ac.noop;
|
|
|
|
config.error = config.error || ac.noop;
|
|
|
|
|
|
|
|
let request = new XMLHttpRequest();
|
|
|
|
let method = String(config.type).toUpperCase();
|
|
|
|
|
2016-02-08 11:32:39 -05:00
|
|
|
if (method === "GET") {
|
|
|
|
url += (url.match(/\?/))
|
|
|
|
? serialize(config.data)
|
|
|
|
: `?${serialize(config.data)}`;
|
|
|
|
}
|
|
|
|
|
2016-02-08 10:57:44 -05:00
|
|
|
request.open(method, url);
|
|
|
|
|
|
|
|
request.onreadystatechange = () => {
|
|
|
|
if (request.readyState === 4) {
|
2016-02-08 13:37:44 -05:00
|
|
|
let responseText = '';
|
|
|
|
|
|
|
|
if (request.responseType == 'json') {
|
|
|
|
responseText = JSON.parse(request.responseText);
|
|
|
|
} else {
|
|
|
|
responseText = request.responseText;
|
|
|
|
}
|
|
|
|
|
2016-02-08 10:57:44 -05:00
|
|
|
if (request.status > 400) {
|
2016-02-08 13:37:44 -05:00
|
|
|
config.error.call(null, request.statusText, request.response);
|
2016-02-08 10:57:44 -05:00
|
|
|
} else {
|
2016-02-08 13:37:44 -05:00
|
|
|
config.success.call(null, responseText, request.status);
|
2016-02-08 10:57:44 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
switch (method) {
|
|
|
|
case "GET":
|
|
|
|
request.send(null);
|
|
|
|
break;
|
|
|
|
|
|
|
|
default:
|
|
|
|
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
|
|
|
|
request.send(serialize(config.data));
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
ac.get = function(url, data, callback) {
|
2016-02-08 11:32:39 -05:00
|
|
|
if (arguments.length === 2) {
|
|
|
|
callback = data;
|
|
|
|
data = {};
|
|
|
|
}
|
|
|
|
|
2016-02-08 10:57:44 -05:00
|
|
|
return ac.ajax(url, {
|
|
|
|
data: data,
|
|
|
|
success: callback
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
return ac;
|
|
|
|
|
|
|
|
})(AnimeClient);
|