Nuestro conocimiento compartido. Nuestro tesoro compartido. Wikipedia.
ShareCode
Permalink: http://www.treeweb.es/u/974/ 01/02/2011

ShareCode

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.callbacks = ({13  progress:null,14  done:null,15  error:null,16  presend:null17  });18  19 };20 21 Ajax.prototype.retry = function() {22  if (null !== this._xhr && that._xhr.readyState === XMLHttpRequest.DONE && that._xhr.status != 0) {23  // Yet finished24  } else {25  null === this._xhr || this._xhr.abort();26  this._xhr = new XMLHttpRequest();27  28  29  30  31  32  33  34  }35 }36 37 Ajax.prototype.send = function(data) {38  this.data = data;39  var that = this;40  41  function go() {42  that._xhr = new XMLHttpRequest();43  that._xhr.timeout = 500;44  that._xhr.open(that.method, that.url, that.async);45  that._xhr.timeout = 500;46  that._xhr.onreadystatechange = function(event) {47  logger.log(that._xhr);48  logger.log({'that._xhr.readyState':that._xhr.readyState});49  if (that._xhr.readyState == XMLHttpRequest.DONE && that._xhr.status != 0) {50  logger.log(that._xhr);51  if (null != that.callbacks.done) {52  that.callbacks.done(that._xhr);53  }54  }55  };56  57  if (null != that.callbacks.presend)58  that.callbacks.presend(that._xhr);59  that._xhr.send(data);60  };61 62  var timer = function() {63  that.retries--;64  if (that.retries >0) { // Retry65  if (that._xhr.readyState != XMLHttpRequest.DONE || that._xhr.status == 0) {66  that._xhr.abort();67  go();68  setTimeout(timer, that.timeout);69  }70  } else { // Throw error71  that._xhr.abort();72  if (null != that.callbacks.error)73  that.callbacks.error({'number':1,'description':'Timeout'});74  }75  };76  77  go();78  setTimeout(timer, that.timeout);79 80  81  82  /*83  void send();84  void send(ArrayBuffer data);85  void send(Blob data);86  void send(Document data);87  void send(DOMString? data);88  void send(FormData data);89  */90  91  92  93 };94 95 Ajax.prototype.abort = function() {96  this._xhr.abort();97  if (null != this.callbacks.error)98  this.callbacks.error({'number':2,'description':'Aborted by user'});99 };100 101 window.addEventListener('load', function(e){102  var a = new Ajax();103  a.url = 'http://www.treeweb.es/request2';104  a.callbacks.done = function(xhr) {105  logger.log(xhr);106  };107  a.callbacks.error = function(error) {108  //logger.log(error);109  }110  a.callbacks.presend = function(xhr) {111  //logger.log(xhr);112  }113  a.send();114  115  logger.show();116 }, true);117 118 119 120 


Este ShareCode tiene versiones:
  1. Ajax Refactor ... (14/12/2012)
  2. Ajax Refactor ... (24/04/2013)
  3. Ajax Refactor ... (24/04/2013)
  4. Ajax Refactor ... (24/04/2013)
  5. Ajax Refactor ... (24/04/2013)
  6. Ajax Refactor ... (24/04/2013)
Enlace
El enlace para compartir es: