1 2 3 var Ajax = function() {4 5 this.url = '';6 this.method = 'GET';7 this.async = true;8 this.retries = 3;9 this.timeout = 4000; // milliseconds10 this.data = null;11 this.callbacks = ({12 progress:null,13 done:null,14 error:null,15 presend:null16 });17 18 };19 20 Ajax.prototype.send = function(data) {21 this.data = data;22 var xhr = new XMLHttpRequest();23 var that = this;24 25 xhr.timeout = this.timeout;26 xhr.open(this.method, this.url, this.async);27 xhr.onreadystatechange = function(event) {28 logger.log({'xhr.readyState':xhr.readyState});29 if (xhr.readyState == XMLHttpRequest.DONE) {30 if (null != that.callbacks.done) {31 that.callbacks.done(xhr);32 }33 }34 35 36 };37 38 if (null != this.callbacks.presend) {39 this.callbacks.presend(xhr);40 }41 42 xhr.send(data);43 44 var timer = function() {45 if (true) {46 that.retries--;47 alert(that.retries);48 if (that.retries >=0) {49 // Retry50 setTimeout(timer, that.timeout);51 } else {52 // Lanza error53 }54 } else {55 setTimeout(timer, that.timeout);56 }57 };58 59 timer();60 61 62 63 /*64 void send();65 void send(ArrayBuffer data);66 void send(Blob data);67 void send(Document data);68 void send(DOMString? data);69 void send(FormData data);70 */71 72 73 74 };75 76 Ajax.prototype.abort = function() {77 this._xhr.abort();78 };79 80 81 82 window.addEventListener('load', function(e){83 var a = new Ajax();84 a.url = 'http://www.treeweb.es/request2';85 a.callbacks.done = function(xhr) {86 alert(xhr.response);87 logger.log(xhr);88 };89 a.send();90 logger.log(a);91 }, true);92 93 94 95
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: