1 2 3 var Ajax = function() {4 5 this._xhr = null;6 this.url = '';7 this.method = 'GET';8 this.async = true;9 this.retries = 3;10 this.timeout = 10000; // milliseconds11 this.data = null;12 this.aborted = false;13 this.callbacks = ({14 progress:null,15 done:null,16 error:null,17 presend:null18 });19 20 };21 22 Ajax.prototype.retry = function() {23 var that = this;24 if (this.aborted) {25 // Yet finished26 } else if (null !== this._xhr && that._xhr.readyState === XMLHttpRequest.DONE && that._xhr.status != 0) {27 // Yet finished28 } else {29 null === this._xhr || this._xhr.abort();30 31 var xhr = this._xhr = new XMLHttpRequest();32 xhr.open(this.method, this.url, this.async);33 xhr.onreadystatechange = function(event) {34 if (xhr.readyState == XMLHttpRequest.DONE && xhr.status != 0) {35 if (null != that.callbacks.done) {36 that.callbacks.done(xhr);37 }38 }39 };40 xhr.send(this.data);41 /*42 if (null != that.callbacks.presend)43 that.callbacks.presend(that._xhr);44 45 */46 }47 }48 49 Ajax.prototype.send = function(data) {50 this.data = data;51 this.aborted = false;52 this.retry();53 };54 55 Ajax.prototype.abort = function() {56 this.aborted = true;57 this._xhr.abort();58 if (null != this.callbacks.error)59 this.callbacks.error({'number':2,'description':'Aborted'});60 };61 62 window.addEventListener('load', function(e){63 var a = new Ajax();64 a.url = 'http://www.treeweb.es/request2';65 a.callbacks.done = function(xhr) {66 logger.log(xhr);67 };68 a.callbacks.error = function(error) {69 logger.log(error);70 }71 a.callbacks.presend = function(xhr) {72 //logger.log(xhr);73 }74 a.send();75 76 logger.show();77 }, true);78 79 80 81
Este ShareCode tiene versiones:
- Ajax Refactor ... (14/12/2012)
- Ajax Refactor ... (24/04/2013)
- Ajax Refactor ... (24/04/2013)
- Ajax Refactor ... (24/04/2013)
- Ajax Refactor ... (24/04/2013)
- Ajax Refactor ... (24/04/2013)
Enlace
El enlace para compartir es: