1 | define([
|
2 | "../core",
|
3 | "../var/support",
|
4 | "../ajax"
|
5 | ], function( jQuery, support ) {
|
6 |
|
7 | jQuery.ajaxSettings.xhr = function() {
|
8 | try {
|
9 | return new XMLHttpRequest();
|
10 | } catch( e ) {}
|
11 | };
|
12 |
|
13 | var xhrId = 0,
|
14 | xhrCallbacks = {},
|
15 | xhrSuccessStatus = {
|
16 |
|
17 | 0: 200,
|
18 |
|
19 |
|
20 | 1223: 204
|
21 | },
|
22 | xhrSupported = jQuery.ajaxSettings.xhr();
|
23 |
|
24 |
|
25 |
|
26 | if ( window.ActiveXObject ) {
|
27 | jQuery( window ).on( "unload", function() {
|
28 | for ( var key in xhrCallbacks ) {
|
29 | xhrCallbacks[ key ]();
|
30 | }
|
31 | });
|
32 | }
|
33 |
|
34 | support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
|
35 | support.ajax = xhrSupported = !!xhrSupported;
|
36 |
|
37 | jQuery.ajaxTransport(function( options ) {
|
38 | var callback;
|
39 |
|
40 |
|
41 | if ( support.cors || xhrSupported && !options.crossDomain ) {
|
42 | return {
|
43 | send: function( headers, complete ) {
|
44 | var i,
|
45 | xhr = options.xhr(),
|
46 | id = ++xhrId;
|
47 |
|
48 | xhr.open( options.type, options.url, options.async, options.username, options.password );
|
49 |
|
50 |
|
51 | if ( options.xhrFields ) {
|
52 | for ( i in options.xhrFields ) {
|
53 | xhr[ i ] = options.xhrFields[ i ];
|
54 | }
|
55 | }
|
56 |
|
57 |
|
58 | if ( options.mimeType && xhr.overrideMimeType ) {
|
59 | xhr.overrideMimeType( options.mimeType );
|
60 | }
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 | if ( !options.crossDomain && !headers["X-Requested-With"] ) {
|
68 | headers["X-Requested-With"] = "XMLHttpRequest";
|
69 | }
|
70 |
|
71 |
|
72 | for ( i in headers ) {
|
73 | xhr.setRequestHeader( i, headers[ i ] );
|
74 | }
|
75 |
|
76 |
|
77 | callback = function( type ) {
|
78 | return function() {
|
79 | if ( callback ) {
|
80 | delete xhrCallbacks[ id ];
|
81 | callback = xhr.onload = xhr.onerror = null;
|
82 |
|
83 | if ( type === "abort" ) {
|
84 | xhr.abort();
|
85 | } else if ( type === "error" ) {
|
86 | complete(
|
87 |
|
88 | xhr.status,
|
89 | xhr.statusText
|
90 | );
|
91 | } else {
|
92 | complete(
|
93 | xhrSuccessStatus[ xhr.status ] || xhr.status,
|
94 | xhr.statusText,
|
95 |
|
96 |
|
97 |
|
98 | typeof xhr.responseText === "string" ? {
|
99 | text: xhr.responseText
|
100 | } : undefined,
|
101 | xhr.getAllResponseHeaders()
|
102 | );
|
103 | }
|
104 | }
|
105 | };
|
106 | };
|
107 |
|
108 |
|
109 | xhr.onload = callback();
|
110 | xhr.onerror = callback("error");
|
111 |
|
112 |
|
113 | callback = xhrCallbacks[ id ] = callback("abort");
|
114 |
|
115 | try {
|
116 |
|
117 | xhr.send( options.hasContent && options.data || null );
|
118 | } catch ( e ) {
|
119 |
|
120 | if ( callback ) {
|
121 | throw e;
|
122 | }
|
123 | }
|
124 | },
|
125 |
|
126 | abort: function() {
|
127 | if ( callback ) {
|
128 | callback();
|
129 | }
|
130 | }
|
131 | };
|
132 | }
|
133 | });
|
134 |
|
135 | });
|