jquery.xdr-transport.js 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * jQuery XDomainRequest Transport Plugin 1.1.4
  3. * https://github.com/blueimp/jQuery-File-Upload
  4. *
  5. * Copyright 2011, Sebastian Tschan
  6. * https://blueimp.net
  7. *
  8. * Licensed under the MIT license:
  9. * http://www.opensource.org/licenses/MIT
  10. *
  11. * Based on Julian Aubourg's ajaxHooks xdr.js:
  12. * https://github.com/jaubourg/ajaxHooks/
  13. */
  14. /* global define, require, window, XDomainRequest */
  15. (function (factory) {
  16. 'use strict';
  17. if (typeof define === 'function' && define.amd) {
  18. // Register as an anonymous AMD module:
  19. define(['jquery'], factory);
  20. } else if (typeof exports === 'object') {
  21. // Node/CommonJS:
  22. factory(require('jquery'));
  23. } else {
  24. // Browser globals:
  25. factory(window.jQuery);
  26. }
  27. }(function ($) {
  28. 'use strict';
  29. if (window.XDomainRequest && !$.support.cors) {
  30. $.ajaxTransport(function (s) {
  31. if (s.crossDomain && s.async) {
  32. if (s.timeout) {
  33. s.xdrTimeout = s.timeout;
  34. delete s.timeout;
  35. }
  36. var xdr;
  37. return {
  38. send: function (headers, completeCallback) {
  39. var addParamChar = /\?/.test(s.url) ? '&' : '?';
  40. function callback(status, statusText, responses, responseHeaders) {
  41. xdr.onload = xdr.onerror = xdr.ontimeout = $.noop;
  42. xdr = null;
  43. completeCallback(status, statusText, responses, responseHeaders);
  44. }
  45. xdr = new XDomainRequest();
  46. // XDomainRequest only supports GET and POST:
  47. if (s.type === 'DELETE') {
  48. s.url = s.url + addParamChar + '_method=DELETE';
  49. s.type = 'POST';
  50. } else if (s.type === 'PUT') {
  51. s.url = s.url + addParamChar + '_method=PUT';
  52. s.type = 'POST';
  53. } else if (s.type === 'PATCH') {
  54. s.url = s.url + addParamChar + '_method=PATCH';
  55. s.type = 'POST';
  56. }
  57. xdr.open(s.type, s.url);
  58. xdr.onload = function () {
  59. callback(
  60. 200,
  61. 'OK',
  62. {text: xdr.responseText},
  63. 'Content-Type: ' + xdr.contentType
  64. );
  65. };
  66. xdr.onerror = function () {
  67. callback(404, 'Not Found');
  68. };
  69. if (s.xdrTimeout) {
  70. xdr.ontimeout = function () {
  71. callback(0, 'timeout');
  72. };
  73. xdr.timeout = s.xdrTimeout;
  74. }
  75. xdr.send((s.hasContent && s.data) || null);
  76. },
  77. abort: function () {
  78. if (xdr) {
  79. xdr.onerror = $.noop();
  80. xdr.abort();
  81. }
  82. }
  83. };
  84. }
  85. });
  86. }
  87. }));