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 = 3000; // 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 this.retries--;24 var that = this;25 26 // Abort current request if exists27 null === this._xhr || this._xhr.abort();28 29 var xhr = this._xhr = new XMLHttpRequest();30 xhr.open(this.method, this.url, this.async);31 xhr.onreadystatechange = function(event) {32 if (xhr.readyState == XMLHttpRequest.DONE && xhr.status != 0) {33 if (null != that.callbacks.done) {34 that.callbacks.done(xhr);35 }36 }37 };38 xhr.onerror = function(event) {39 if (null != that.callbacks.error)40 that.callbacks.error({'number':3,'description':'Connection refused'});41 }42 if (null != this.callbacks.presend)43 this.callbacks.presend(that._xhr);44 xhr.send(this.data);45 46 setTimeout(function() {47 if (that.aborted) {48 // WAS ABORTED49 } else if (null !== that._xhr && that._xhr.readyState === XMLHttpRequest.DONE && that._xhr.status != 0) {50 // ALL OK51 } else if (that.retries<=0) {52 null === that._xhr || that._xhr.abort();53 if (null != that.callbacks.error)54 that.callbacks.error({'number':1,'description':'Timeout'});55 } else {56 that.retry();57 }58 }, this.timeout);59 }60 61 Ajax.prototype.send = function(data) {62 var that = this;63 64 this.data = data;65 this.aborted = false;66 this.retry();67 };68 69 Ajax.prototype.abort = function() {70 this.aborted = true;71 null === this._xhr || this._xhr.abort();72 if (null != this.callbacks.error)73 this.callbacks.error({'number':2,'description':'Aborted'});74 };75 76 window.addEventListener('load', function(e){77 var a = new Ajax();78 a.url = 'http://www.treeweb.es/request2';79 a.callbacks.done = function(xhr) {80 logger.log(a);81 };82 a.callbacks.error = function(error) {83 logger.log(error);84 }85 a.callbacks.presend = function(xhr) {86 //logger.log(xhr);87 }88 a.send('');89 90 logger.show();91 }, true);92 93 94 95
Este ShareCode tiene versiones:
- 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: