Created
January 7, 2016 09:52
-
-
Save a-c-t-i-n-i-u-m/5bfeb14ef4761e790264 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
// interface | |
var ajax = function (args) { | |
return new ajaxObject(args); | |
}; | |
// object | |
var ajaxObject = function (args) { | |
// init | |
this.request = new XMLHttpRequest(); | |
// send request | |
if (!args || !args.url) { | |
throw new Error('args.url is empty!'); | |
} | |
this.request.open(args.method || 'GET', args.url); | |
if (args.noCache || args.cache === false) { | |
this.request.setRequestHeader('If-Modified-Since', 'Thu, 01 Jun 1970 00:00:00 GMT'); | |
this.request.setRequestHeader('Pragma', 'no-cache'); | |
this.request.setRequestHeader('Cache-Control', 'no-cache'); | |
} | |
if (args.cookie || args.withCredentials) { | |
this.request.withCredentials = true; | |
} | |
this.request.send(args.data || null); | |
}; | |
// callback | |
ajaxObject.prototype.success = function (fn) { | |
return this.addEventListener('load', fn); | |
}; | |
ajaxObject.prototype.error = function (fn) { | |
return this.addEventListener('error', fn); | |
}; | |
ajaxObject.prototype.done = function (fn) { | |
return this.addEventListener('loadend', fn); | |
}; | |
ajaxObject.prototype.addEventListener = function (evt, fn) { | |
var instance = this; | |
var caller = function (e) { | |
fn.call(instance, this, e); | |
}; | |
if (this.request.addEventListener) { | |
this.request.addEventListener(evt, caller); | |
} else { | |
// if you need to support <=ie8, implement here. or ignore events when ie8 | |
} | |
return this; | |
}; | |
// export | |
window.ajax = ajax; | |
})(); | |
//(function(){var f=function(a){return new g(a)};var g=function(a){this.request=new XMLHttpRequest();if(!a||!a.url){throw new Error('args.url is empty!');}this.request.open(a.method||'GET',a.url);if(a.noCache||a.cache===false){this.request.setRequestHeader('If-Modified-Since','Thu, 01 Jun 1970 00:00:00 GMT');this.request.setRequestHeader('Pragma','no-cache');this.request.setRequestHeader('Cache-Control','no-cache')}if(a.cookie||a.withCredentials){this.request.withCredentials=true}this.request.send(a.data||null)};g.prototype.success=function(a){return this.addEventListener('load',a)};g.prototype.error=function(a){return this.addEventListener('error',a)};g.prototype.done=function(a){return this.addEventListener('loadend',a)};g.prototype.addEventListener=function(a,b){var c=this;var d=function(e){b.call(c,this,e)};if(this.request.addEventListener){this.request.addEventListener(a,d)}else{}return this};window.ajax=f})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment