1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
|
(function( jQuery ) {
var rquery_xhr = /\?/,
rhash = /#.*$/,
rheaders = /^(.*?):\s*(.*?)\r?$/mg, // IE leaves an \r character at EOL
rnoContent = /^(?:GET|HEAD)$/,
rts = /([?&])_=[^&]*/,
rurl = /^(\w+:)?\/\/([^\/?#]+)/,
sliceFunc = Array.prototype.slice,
isFunction = jQuery.isFunction;
// Creates a jQuery xhr object
jQuery.xhr = function( _native ) {
if ( _native ) {
return jQuery.ajaxSettings.xhr();
}
function reset(force) {
// We only need to reset if we went through the init phase
// (with the exception of object creation)
if ( force || internal ) {
// Reset callbacks lists
callbacksLists = {
success: createCBList(),
error: createCBList(),
complete: createCBList()
};
// Reset private variables
requestHeaders = {};
responseHeadersString = responseHeaders = internal = done = timeoutTimer = s = undefined;
// Reset state
xhr.readyState = 0;
sendFlag = 0;
// Remove responseX fields
for ( var name in xhr ) {
if ( /^response/.test(name) ) {
delete xhr[name];
}
}
}
}
function init() {
var // Options extraction
// Remove hash character (#7531: first for string promotion)
url = s.url = ( "" + s.url ).replace( rhash , "" ),
// Uppercase the type
type = s.type = s.type.toUpperCase(),
// Determine if request has content
hasContent = s.hasContent = ! rnoContent.test( type ),
// Extract dataTypes list
dataType = s.dataType,
dataTypes = s.dataTypes = dataType ? jQuery.trim(dataType).toLowerCase().split(/\s+/) : ["*"],
// Determine if a cross-domain request is in order
parts = rurl.exec( url.toLowerCase() ),
loc = location,
crossDomain = s.crossDomain = !!( parts && ( parts[1] && parts[1] != loc.protocol || parts[2] != loc.host ) ),
// Get other options locally
data = s.data,
originalContentType = s.contentType,
prefilters = s.prefilters,
accepts = s.accepts,
headers = s.headers,
// Other Variables
transportDataType,
i;
// Convert data if not already a string
if ( data && s.processData && typeof data != "string" ) {
data = s.data = jQuery.param( data , s.traditional );
}
// Apply option prefilters
for (i in prefilters) {
prefilters[i](s);
}
// Get internal
internal = selectTransport( s );
// Re-actualize url & data
url = s.url;
data = s.data;
// If internal was found
if ( internal ) {
// Get transportDataType
transportDataType = dataTypes[0];
// More options handling for requests with no content
if ( ! hasContent ) {
// If data is available, append data to url
if ( data ) {
url += (rquery_xhr.test(url) ? "&" : "?") + data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = url.replace(rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
url = ret + ((ret == url) ? (rquery_xhr.test(url) ? "&" : "?") + "_=" + ts : "");
}
s.url = url;
}
// Set the correct header, if data is being sent
if ( ( data && hasContent ) || originalContentType ) {
requestHeaders["content-type"] = s.contentType;
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery_lastModified[url] ) {
requestHeaders["if-modified-since"] = jQuery_lastModified[url];
}
if ( jQuery_etag[url] ) {
requestHeaders["if-none-match"] = jQuery_etag[url];
}
}
// Set the Accepts header for the server, depending on the dataType
requestHeaders.accept = transportDataType && accepts[ transportDataType ] ?
accepts[ transportDataType ] + ( transportDataType !== "*" ? ", */*; q=0.01" : "" ) :
accepts[ "*" ];
// Check for headers option
for ( i in headers ) {
requestHeaders[ i.toLowerCase() ] = headers[ i ];
}
}
callbackContext = s.context || s;
globalEventContext = s.context ? jQuery(s.context) : jQuery.event;
for ( i in callbacksLists ) {
callbacksLists[i].bind(s[i]);
}
// Watch for a new set of requests
if ( s.global && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
done = whenDone;
}
function whenDone(status, statusText, response, headers) {
// Called once
done = undefined;
// Reset sendFlag
sendFlag = 0;
// Cache response headers
responseHeadersString = headers || "";
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout(timeoutTimer);
}
var // Reference url
url = s.url,
// and ifModified status
ifModified = s.ifModified,
// Is it a success?
isSuccess = 0,
// Stored success
success,
// Stored error
error = statusText;
// If not timeout, force a jQuery-compliant status text
if ( statusText != "timeout" ) {
statusText = ( status >= 200 && status < 300 ) ?
"success" :
( status === 304 ? "notmodified" : "error" );
}
// If successful, handle type chaining
if ( statusText === "success" || statusText === "notmodified" ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( ifModified ) {
var lastModified = xhr.getResponseHeader("Last-Modified"),
etag = xhr.getResponseHeader("Etag");
if (lastModified) {
jQuery_lastModified[url] = lastModified;
}
if (etag) {
jQuery_etag[url] = etag;
}
}
if ( ifModified && statusText === "notmodified" ) {
success = null;
isSuccess = 1;
} else {
// Chain data conversions and determine the final value
// (if an exception is thrown in the process, it'll be notified as an error)
try {
function checkData(data) {
if ( data !== undefined ) {
var testFunction = s.dataCheckers[srcDataType];
if ( isFunction( testFunction ) ) {
testFunction(data);
}
}
}
function convertData (data) {
var conversionFunction = dataConverters[srcDataType+" => "+destDataType] ||
dataConverters["* => "+destDataType],
noFunction = ! isFunction( conversionFunction );
if ( noFunction ) {
if ( srcDataType != "text" && destDataType != "text" ) {
// We try to put text inbetween
var first = dataConverters[srcDataType+" => text"] ||
dataConverters["* => text"],
second = dataConverters["text => "+destDataType] ||
dataConverters["* => "+destDataType],
areFunctions = isFunction( first ) && isFunction( second );
if ( areFunctions ) {
conversionFunction = function (data) {
return second( first ( data ) );
};
}
noFunction = ! areFunctions;
}
if ( noFunction ) {
jQuery.error( "no data converter between " + srcDataType + " and " + destDataType );
}
}
return conversionFunction(data);
}
var dataTypes = s.dataTypes,
i,
length,
data = response,
dataConverters = s.dataConverters,
srcDataType,
destDataType,
responseTypes = s.xhrResponseFields;
for ( i = 0, length = dataTypes.length ; i < length ; i++ ) {
destDataType = dataTypes[i];
if ( !srcDataType ) { // First time
// Copy type
srcDataType = destDataType;
// Check
checkData(data);
// Apply dataFilter
if ( isFunction( s.dataFilter ) ) {
data = s.dataFilter(data, s.dataType);
// Recheck data
checkData(data);
}
} else { // Subsequent times
// handle auto
// JULIAN: for reasons unknown to me === doesn't work here
if (destDataType == "*") {
destDataType = srcDataType;
} else if ( srcDataType != destDataType ) {
// Convert
data = convertData(data);
// Copy type & check
srcDataType = destDataType;
checkData(data);
}
}
// Copy response into the xhr if it hasn't been already
var responseDataType,
responseType = responseTypes[srcDataType];
if ( responseType ) {
responseDataType = srcDataType;
} else {
responseType = responseTypes[ responseDataType = "text" ];
}
if ( responseType !== 1 ) {
xhr[ "response" + responseType ] = data;
responseTypes[ responseType ] = 1;
}
}
// We have a real success
success = data;
isSuccess = 1;
} catch(e) {
statusText = "parsererror";
error = "" + e;
}
}
} else { // if not success, mark it as an error
error = error || statusText;
}
// Set data for the fake xhr object
xhr.status = status;
xhr.statusText = statusText;
// Keep local copies of vars in case callbacks re-use the xhr
var _s = s,
_callbacksLists = callbacksLists,
_callbackContext = callbackContext,
_globalEventContext = globalEventContext;
// Set state if the xhr hasn't been re-used
function _setState( value ) {
if ( xhr.readyState && s === _s ) {
setState( value );
}
}
// Really completed?
if ( status && s.async ) {
setState( 2 );
_setState( 3 );
}
// We're done
_setState( 4 );
// Success
_callbacksLists.success.fire( isSuccess , _callbackContext , success, statusText, xhr);
if ( isSuccess && _s.global ) {
_globalEventContext.trigger( "ajaxSuccess", [xhr, _s, success] );
}
// Error
_callbacksLists.error.fire( ! isSuccess , _callbackContext , xhr, statusText, error);
if ( !isSuccess && _s.global ) {
_globalEventContext.trigger( "ajaxError", [xhr, _s, error] );
}
// Complete
_callbacksLists.complete.fire( 1 , _callbackContext, xhr, statusText);
if ( _s.global ) {
_globalEventContext.trigger( "ajaxComplete", [xhr, _s] );
// Handle the global AJAX counter
if ( ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Ready state control
function checkState( expected , test ) {
if ( expected !== true && ( expected === false || test === false || xhr.readyState !== expected ) ) {
jQuery.error("INVALID_STATE_ERR");
}
}
// Ready state change
function setState( value ) {
xhr.readyState = value;
if ( isFunction( xhr.onreadystatechange ) ) {
xhr.onreadystatechange();
}
}
var // jQuery lists
jQuery_lastModified = jQuery.lastModified,
jQuery_etag = jQuery.etag,
// Options object
s,
// Callback stuff
callbackContext,
globalEventContext,
callbacksLists,
// Headers (they are sent all at once)
requestHeaders,
// Response headers
responseHeadersString,
responseHeaders,
// Done callback
done,
// transport
internal,
// timeout handle
timeoutTimer,
// The send flag
sendFlag,
// Fake xhr
xhr = {
// state
readyState: 0,
// Callback
onreadystatechange: null,
// Open
open: function(type, url, async, username, password) {
xhr.abort();
reset();
s = {
type: type,
url: url,
async: async,
username: username,
password: password
};
setState(1);
return xhr;
},
// Send
send: function(data, moreOptions) {
checkState(1 , !sendFlag);
s.data = data;
s = jQuery.extend( true,
{},
jQuery.ajaxSettings,
s,
moreOptions || ( moreOptions === false ? { global: false } : {} ) );
if ( moreOptions ) {
// We force the original context
// (plain objects used as context get extended)
s.context = moreOptions.context;
}
init();
// If not internal, abort
if ( ! internal ) {
done( 0 , "transport not found" );
return false;
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend ) {
var _s = s;
if ( s.beforeSend.call(callbackContext, xhr, s) === false || ! xhr.readyState || _s !== s ) {
// Abort if not done
if ( xhr.readyState && _s === s ) {
xhr.abort();
}
// Handle the global AJAX counter
if ( _s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
return false;
}
}
sendFlag = 1;
// Send global event
if ( s.global ) {
globalEventContext.trigger("ajaxSend", [xhr, s]);
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function(){
xhr.abort("timeout");
}, s.timeout);
}
if ( s.async ) {
setState(1);
}
try {
internal.send(requestHeaders, done);
return xhr;
} catch (e) {
if ( done ) {
done(0, "error", "" + e);
} else {
jQuery.error(e);
}
}
return false;
},
// Caches the header
setRequestHeader: function(name,value) {
checkState(1, !sendFlag);
requestHeaders[ name.toLowerCase() ] = value;
return xhr;
},
// Raw string
getAllResponseHeaders: function() {
return xhr.readyState <= 1 ? "" : responseHeadersString;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
if ( xhr.readyState <= 1 ) {
return null;
}
if ( responseHeaders === undefined ) {
responseHeaders = {};
if ( typeof responseHeadersString === "string" ) {
var match;
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
}
}
}
return responseHeaders[ key.toLowerCase() ];
},
// Cancel the request
abort: function(statusText) {
if (internal) {
internal.abort( statusText || "abort" );
}
xhr.readyState = 0;
}
};
// Init data (so that we can bind callbacks early
reset(1);
// Install callbacks related methods
jQuery.each(callbacksLists, function(name) {
var list;
xhr[name] = function() {
list = callbacksLists[name];
if ( list ) {
list.bind.apply(list, arguments );
}
return this;
};
});
// Return the xhr emulation
return xhr;
};
// Create a callback list
function createCBList() {
var functors = [],
autoFire = 0,
fireArgs,
list = {
fire: function( flag , context ) {
// Save info for later bindings
fireArgs = arguments;
// Remove autoFire to keep bindings in order
autoFire = 0;
var args = sliceFunc.call( fireArgs , 2 );
// Execute callbacks
while ( flag && functors.length ) {
flag = functors.shift().apply( context , args ) !== false;
}
// Clean if asked to stop
if ( ! flag ) {
clean();
}
// Set autoFire
autoFire = 1;
},
bind: function() {
var args = arguments,
i = 0,
length = args.length,
func;
for ( ; i < length ; i++ ) {
func = args[ i ];
if ( jQuery.isArray(func) ) {
list.bind.apply( list , func );
} else if ( isFunction(func) ) {
// Add if not already in
if ( ! pos( func ) ) {
functors.push( func );
}
}
}
if ( autoFire ) {
list.fire.apply( list , fireArgs );
}
},
unbind: function() {
var i = 0,
args = arguments,
length = args.length,
func,
position;
if ( length ) {
for( ; i < length ; i++ ) {
func = args[i];
if ( jQuery.isArray(func) ) {
list.unbind.apply(list,func);
} else if ( isFunction(func) ) {
position = pos(func);
if ( position ) {
functors.splice(position-1,1);
}
}
}
} else {
functors = [];
}
}
};
// Get the index of the functor in the list (1-based)
function pos( func ) {
for (var i = 0, length = functors.length; i < length && functors[i] !== func; i++) {
}
return i < length ? ( i + 1 ) : 0;
}
// Clean the object
function clean() {
// Empty callbacks list
functors = [];
// Inhibit methods
for (var i in list) {
list[i] = jQuery.noop;
}
}
return list;
}
jQuery.extend(jQuery.xhr, {
// Add new prefilter
prefilter: function (functor) {
if ( isFunction(functor) ) {
jQuery.ajaxSettings.prefilters.push( functor );
}
return this;
},
// Bind a transport to one or more dataTypes
bindTransport: function () {
var args = arguments,
i,
start = 0,
length = args.length,
dataTypes = [ "*" ],
functors = [],
functor,
first,
append,
list,
transports = jQuery.ajaxSettings.transports;
if ( length ) {
if ( ! isFunction( args[ 0 ] ) ) {
dataTypes = args[ 0 ].toLowerCase().split(/\s+/);
start = 1;
}
if ( dataTypes.length && start < length ) {
for ( i = start; i < length; i++ ) {
functor = args[i];
if ( isFunction(functor) ) {
functors.push( functor );
}
}
if ( functors.length ) {
jQuery.each ( dataTypes, function( _ , dataType ) {
first = /^\+/.test( dataType );
if (first) {
dataType = dataType.substr(1);
}
if ( dataType !== "" ) {
append = Array.prototype[ first ? "unshift" : "push" ];
list = transports[ dataType ];
jQuery.each ( functors, function( _ , functor ) {
if ( ! list ) {
list = transports[ dataType ] = [ functor ];
} else {
append.call( list , functor );
}
} );
}
} );
}
}
}
return this;
}
});
// Select a transport given options
function selectTransport( s ) {
var dataTypes = s.dataTypes,
transportDataType,
transportsList,
transport,
i,
length,
checked = {},
flag;
function initSearch( dataType ) {
flag = transportDataType !== dataType && ! checked[ dataType ];
if ( flag ) {
checked[ dataType ] = 1;
transportDataType = dataType;
transportsList = s.transports[ dataType ];
i = -1;
length = transportsList ? transportsList.length : 0 ;
}
return flag;
}
initSearch( dataTypes[ 0 ] );
for ( i = 0 ; ! transport && i <= length ; i++ ) {
if ( i === length ) {
initSearch( "*" );
} else {
transport = transportsList[ i ]( s , determineDataType );
// If we got redirected to another dataType
// Search there (if not in progress or already tried)
if ( typeof( transport ) === "string" &&
initSearch( transport ) ) {
dataTypes.unshift( transport );
transport = 0;
}
}
}
return transport;
}
// Utility function that handles dataType when response is received
// (for those transports that can give text or xml responses)
function determineDataType( s , ct , text , xml ) {
var autoDataType = s.autoDataType,
type,
regexp,
dataTypes = s.dataTypes,
transportDataType = dataTypes[0],
response;
// Auto (xml, json, script or text determined given headers)
if ( transportDataType === "*" ) {
for ( type in autoDataType ) {
if ( ( regexp = autoDataType[ type ] ) && regexp.test( ct ) ) {
transportDataType = dataTypes[0] = type;
break;
}
}
}
// xml and parsed as such
if ( transportDataType === "xml" &&
xml &&
xml.documentElement /* #4958 */ ) {
response = xml;
// Text response was provided
} else {
response = text;
// If it's not really text, defer to dataConverters
if ( transportDataType !== "text" ) {
dataTypes.unshift( "text" );
}
}
return response;
}
})( jQuery );
|