XHR.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * XHR.js
  3. *
  4. * Copyright, Moxiecode Systems AB
  5. * Released under LGPL License.
  6. *
  7. * License: http://www.tinymce.com/license
  8. * Contributing: http://www.tinymce.com/contributing
  9. */
  10. /**
  11. * This class enables you to send XMLHTTPRequests cross browser.
  12. * @class tinymce.util.XHR
  13. * @static
  14. * @example
  15. * // Sends a low level Ajax request
  16. * tinymce.util.XHR.send({
  17. * url: 'someurl',
  18. * success: function(text) {
  19. * console.debug(text);
  20. * }
  21. * });
  22. */
  23. define("tinymce/util/XHR", [], function() {
  24. return {
  25. /**
  26. * Sends a XMLHTTPRequest.
  27. * Consult the Wiki for details on what settings this method takes.
  28. *
  29. * @method send
  30. * @param {Object} settings Object will target URL, callbacks and other info needed to make the request.
  31. */
  32. send: function(settings) {
  33. var xhr, count = 0;
  34. function ready() {
  35. if (!settings.async || xhr.readyState == 4 || count++ > 10000) {
  36. if (settings.success && count < 10000 && xhr.status == 200) {
  37. settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings);
  38. } else if (settings.error) {
  39. settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings);
  40. }
  41. xhr = null;
  42. } else {
  43. setTimeout(ready, 10);
  44. }
  45. }
  46. // Default settings
  47. settings.scope = settings.scope || this;
  48. settings.success_scope = settings.success_scope || settings.scope;
  49. settings.error_scope = settings.error_scope || settings.scope;
  50. settings.async = settings.async === false ? false : true;
  51. settings.data = settings.data || '';
  52. xhr = new XMLHttpRequest();
  53. if (xhr) {
  54. if (xhr.overrideMimeType) {
  55. xhr.overrideMimeType(settings.content_type);
  56. }
  57. xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async);
  58. if (settings.content_type) {
  59. xhr.setRequestHeader('Content-Type', settings.content_type);
  60. }
  61. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  62. xhr.send(settings.data);
  63. // Syncronous request
  64. if (!settings.async) {
  65. return ready();
  66. }
  67. // Wait for response, onReadyStateChange can not be used since it leaks memory in IE
  68. setTimeout(ready, 10);
  69. }
  70. }
  71. };
  72. });