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 = 1000; // 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 var that = this;51 52 this.data = data;53 this.aborted = false;54 this.retry();55 if (this.retries > 0)56 setTimeout(function() {57 this.retries--;58 that._xhr.abort();59 that._xhr = null;60 that.retry();61 }, this.timeout);62 };63 64 Ajax.prototype.abort = function() {65 this.aborted = true;66 this._xhr.abort();67 if (null != this.callbacks.error)68 this.callbacks.error({'number':2,'description':'Aborted'});69 };70 71 window.addEventListener('load', function(e){72 var a = new Ajax();73 a.url = 'http://www.treeweb.es/request2';74 a.callbacks.done = function(xhr) {75 logger.log(xhr);76 };77 a.callbacks.error = function(error) {78 logger.log(error);79 }80 a.callbacks.presend = function(xhr) {81 //logger.log(xhr);82 }83 a.send();84 85 logger.show();86 }, true);87 88 89 90
Este ShareCode tiene versiones:
- Cargando...... (19/12/2012)
- Cargando...... (19/12/2012)
- Ajax Refactor v0.17 ... (19/12/2012)
- Ajax Refactor v0.17 ... (24/04/2013)
- Ajax Refactor v0.17 ... (24/04/2013)
- Ajax Refactor v0.17 ... (24/04/2013)
- Ajax Refactor v0.17 ... (24/04/2013)
- Ajax Refactor v0.17 ... (24/04/2013)
Enlace
El enlace para compartir es: