jquery.ajax-retry.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * jquery.ajax-retry
  3. * https://github.com/johnkpaul/jquery-ajax-retry
  4. *
  5. * Copyright (c) 2012 John Paul
  6. * Licensed under the MIT license.
  7. */
  8. (function($) {
  9. // enhance all ajax requests with our retry API
  10. $.ajaxPrefilter(function(options, originalOptions, jqXHR){
  11. jqXHR.retry = function(opts){
  12. if(opts.timeout){
  13. this.timeout = opts.timeout;
  14. }
  15. return this.pipe(null, pipeFailRetry(this, opts.times));
  16. };
  17. });
  18. // generates a fail pipe function that will retry `jqXHR` `times` more times
  19. function pipeFailRetry(jqXHR, times){
  20. // takes failure data as input, returns a new deferred
  21. return function(input, status, msg){
  22. var ajaxOptions = this;
  23. var output = new $.Deferred();
  24. // whenever we do make this request, pipe its output to our deferred
  25. function nextRequest() {
  26. $.ajax(ajaxOptions)
  27. .retry({times:times-1})
  28. .pipe(output.resolve, output.reject);
  29. }
  30. if(times > 1){
  31. // time to make that next request...
  32. if(jqXHR.timeout !== undefined){
  33. setTimeout(nextRequest, jqXHR.timeout);
  34. } else {
  35. nextRequest();
  36. }
  37. } else {
  38. // no times left, reject our deferred with the current arguments
  39. output.rejectWith(this, arguments);
  40. }
  41. return output;
  42. };
  43. }
  44. }(jQuery));