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.send = function(data) {22  this.data = data;23  var that = this;24  25  function go() {26  that._xhr = new XMLHttpRequest();27  that._xhr.open(that.method, that.url, that.async);28  that._xhr.onreadystatechange = function(event) {29  logger.log({'that._xhr.readyState':that._xhr.readyState});30  if (that._xhr.readyState == XMLHttpRequest.DONE && that._xhr.status != 0) {31  logger.log(that._xhr);32  if (null != that.callbacks.done) {33  that.callbacks.done(that._xhr);34  }35  }36  };37  38  if (null != that.callbacks.presend)39  that.callbacks.presend(that._xhr);40  that._xhr.send(data);41  };42 43  var timer = function() {44  that.retries--;45  if (that.retries >0) { // Retry46  if (that._xhr.readyState != XMLHttpRequest.DONE || that._xhr.status == 0) {47  that._xhr.abort();48  go();49  setTimeout(timer, that.timeout);50  }51  } else { // Throw error52  that._xhr.abort();53  if (null != that.callbacks.error)54  that.callbacks.error({'number':1,'description':'Timeout'});55  }56  };57  58  go();59  setTimeout(timer, that.timeout);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  if (null != this.callbacks.error)79  this.callbacks.error({'number':2,'description':'Aborted by user'});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  //logger.log(xhr);87  };88  a.callbacks.error = function(error) {89  //logger.log(error);90  }91  a.callbacks.presend = function(xhr) {92  //logger.log(xhr);93  }94  a.send();95  96  logger.show();97 }, true);98 99 100 101 


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: