refactor(loader) ajax

This commit is contained in:
coderaiser 2014-02-12 02:59:17 -05:00
parent e022369e26
commit eed5d0807b

View file

@ -42,65 +42,61 @@ var Util, DOM;
*
* @param pParams
*/
this.ajax = function(pParams) {
var xhr, p, lType,
lRet = Util.checkObjTrue(pParams, ['url', 'success']);
if (lRet) {
p = pParams,
lType = p.type || p.method || 'GET';
this.ajax = function(params) {
var p = params,
type = p.type || p.method || 'GET',
xhr = new XMLHttpRequest();
xhr.open(lType, pParams.url, true);
if (p.responseType)
xhr.responseType = p.responseType;
Events.add('progress', function(event) {
var percent, count, msg;
if (event.lengthComputable) {
percent = (event.loaded / event.total) * 100,
count = Math.round(percent),
msg = lType + ' ' + p.url + ': ' + count + '%';
Util.log(msg);
}
}, xhr.upload);
Events.add('readystatechange', function(pEvent) {
if (xhr.readyState === 4 /* Complete */) {
var lJqXHR = pEvent.target,
TYPE_JSON = 'application/json',
lType = xhr.getResponseHeader('content-type');
if (xhr.status === 200 /* OK */) {
var lData = lJqXHR.response;
if (p.dataType !== 'text')
/* If it's json - parse it as json */
if (lType && Util.isContainStr(lType, TYPE_JSON))
lData = Util.parseJSON(lJqXHR.response) || lJqXHR.response;
Util.exec(p.success, lData, lJqXHR.statusText, lJqXHR);
}
/* file not found or connection lost */
else {
/* if html given or something like thet
* getBack just status of result
*/
if (lType && lType.indexOf('text/plain') !== 0)
lJqXHR.responseText = lJqXHR.statusText;
Util.exec(p.error, lJqXHR);
}
}
}, xhr);
xhr.send(p.data);
}
return lRet;
xhr.open(type, p.url, true);
if (p.responseType)
xhr.responseType = p.responseType;
Events.add('progress', function(event) {
var percent, count, msg;
if (event.lengthComputable) {
percent = (event.loaded / event.total) * 100,
count = Math.round(percent),
msg = type + ' ' + p.url + ': ' + count + '%';
Util.log(msg);
}
}, xhr.upload);
Events.add('readystatechange', function(event) {
var TYPE_JSON, type, data, isContain,
xhr = event.target;
if (xhr.readyState === 4 /* Complete */) {
TYPE_JSON = 'application/json';
type = xhr.getResponseHeader('content-type');
if (xhr.status === 200 /* OK */) {
data = xhr.response;
isContain = Util.isContainStr(type, TYPE_JSON);
if (p.dataType !== 'text')
/* If it's json - parse it as json */
if (type && isContain)
data = Util.parseJSON(xhr.response) || xhr.response;
Util.exec(p.success, data, xhr.statusText, xhr);
}
/* file not found or connection lost */
else {
/* if html given or something like thet
* getBack just status of result
*/
if (type && type.indexOf('text/plain') !== 0)
xhr.responseText = xhr.statusText;
Util.exec(p.error, xhr);
}
}
}, xhr);
xhr.send(p.data);
};
/**