3 var jsc = jQuery.now(),
4 rscript = /<script(.|\s)*?\/script>/gi,
5 rselectTextarea = /select|textarea/i,
6 rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,
9 rts = /(\?|&)_=.*?(&|$)/,
10 rurl = /^(\w+:)?\/\/([^\/?#]+)/,
13 // Keep a copy of the old load method
14 _load = jQuery.fn.load;
17 load: function( url, params, callback ) {
18 if ( typeof url !== "string" && _load ) {
19 return _load.apply( this, arguments );
21 // Don't do a request if no elements are being requested
22 } else if ( !this.length ) {
26 var off = url.indexOf(" ");
28 var selector = url.slice(off, url.length);
29 url = url.slice(0, off);
32 // Default to a GET request
35 // If the second parameter was provided
38 if ( jQuery.isFunction( params ) ) {
39 // We assume that it's the callback
43 // Otherwise, build a param string
44 } else if ( typeof params === "object" ) {
45 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
52 // Request the remote document
58 complete: function( res, status ) {
59 // If successful, inject the HTML into all the matched elements
60 if ( status === "success" || status === "notmodified" ) {
61 // See if a selector was specified
63 // Create a dummy div to hold the results
65 // inject the contents of the document in, removing the scripts
66 // to avoid any 'Permission Denied' errors in IE
67 .append(res.responseText.replace(rscript, ""))
69 // Locate the specified elements
72 // If not, just inject the full result
77 self.each( callback, [res.responseText, status, res] );
85 serialize: function() {
86 return jQuery.param(this.serializeArray());
89 serializeArray: function() {
90 return this.map(function() {
91 return this.elements ? jQuery.makeArray(this.elements) : this;
94 return this.name && !this.disabled &&
95 (this.checked || rselectTextarea.test(this.nodeName) ||
96 rinput.test(this.type));
98 .map(function( i, elem ) {
99 var val = jQuery(this).val();
103 jQuery.isArray(val) ?
104 jQuery.map( val, function( val, i ) {
105 return { name: elem.name, value: val };
107 { name: elem.name, value: val };
112 // Attach a bunch of functions for handling common AJAX events
113 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
114 jQuery.fn[o] = function( f ) {
115 return this.bind(o, f);
120 get: function( url, data, callback, type ) {
121 // shift arguments if data argument was omited
122 if ( jQuery.isFunction( data ) ) {
123 type = type || callback;
137 getScript: function( url, callback ) {
138 return jQuery.get(url, null, callback, "script");
141 getJSON: function( url, data, callback ) {
142 return jQuery.get(url, data, callback, "json");
145 post: function( url, data, callback, type ) {
146 // shift arguments if data argument was omited
147 if ( jQuery.isFunction( data ) ) {
148 type = type || callback;
162 ajaxSetup: function( settings ) {
163 jQuery.extend( jQuery.ajaxSettings, settings );
170 contentType: "application/x-www-form-urlencoded",
180 // Create the request object; Microsoft failed to properly
181 // implement the XMLHttpRequest in IE7 (can't request local files),
182 // so we use the ActiveXObject when it is available
183 // This function can be overriden by calling jQuery.ajaxSetup
184 xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
186 return new window.XMLHttpRequest();
190 return new window.ActiveXObject("Microsoft.XMLHTTP");
194 xml: "application/xml, text/xml",
196 script: "text/javascript, application/javascript",
197 json: "application/json, text/javascript",
203 ajax: function( origSettings ) {
204 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
205 jsonp, status, data, type = s.type.toUpperCase();
207 s.context = origSettings && origSettings.context || s;
209 // convert data if not already a string
210 if ( s.data && s.processData && typeof s.data !== "string" ) {
211 s.data = jQuery.param( s.data, s.traditional );
214 // Handle JSONP Parameter Callbacks
215 if ( s.dataType === "jsonp" ) {
216 if ( type === "GET" ) {
217 if ( !jsre.test( s.url ) ) {
218 s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
220 } else if ( !s.data || !jsre.test(s.data) ) {
221 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
226 // Build temporary JSONP function
227 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
228 jsonp = s.jsonpCallback || ("jsonp" + jsc++);
230 // Replace the =? sequence both in the query string and the data
232 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
235 s.url = s.url.replace(jsre, "=" + jsonp + "$1");
237 // We need to make sure
238 // that a JSONP style response is executed properly
239 s.dataType = "script";
241 // Handle JSONP-style loading
242 var customJsonp = window[ jsonp ];
244 window[ jsonp ] = function( tmp ) {
246 jQuery.ajax.handleSuccess( s, xhr, status, data );
247 jQuery.ajax.handleComplete( s, xhr, status, data );
249 if ( jQuery.isFunction( customJsonp ) ) {
254 window[ jsonp ] = undefined;
257 delete window[ jsonp ];
258 } catch( jsonpError ) {}
262 head.removeChild( script );
267 if ( s.dataType === "script" && s.cache === null ) {
271 if ( s.cache === false && type === "GET" ) {
272 var ts = jQuery.now();
274 // try replacing _= if it is there
275 var ret = s.url.replace(rts, "$1_=" + ts + "$2");
277 // if nothing was replaced, add timestamp to the end
278 s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
281 // If data is available, append data to url for get requests
282 if ( s.data && type === "GET" ) {
283 s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
286 // Watch for a new set of requests
287 if ( s.global && jQuery.ajax.active++ === 0 ) {
288 jQuery.event.trigger( "ajaxStart" );
291 // Matches an absolute URL, and saves the domain
292 var parts = rurl.exec( s.url ),
293 remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
295 // If we're requesting a remote document
296 // and trying to load JSON or Script with a GET
297 if ( s.dataType === "script" && type === "GET" && remote ) {
298 var head = document.getElementsByTagName("head")[0] || document.documentElement;
299 var script = document.createElement("script");
301 if ( s.scriptCharset ) {
302 script.charset = s.scriptCharset;
305 // Handle Script loading
309 // Attach handlers for all browsers
310 script.onload = script.onreadystatechange = function() {
311 if ( !done && (!this.readyState ||
312 this.readyState === "loaded" || this.readyState === "complete") ) {
314 jQuery.ajax.handleSuccess( s, xhr, status, data );
315 jQuery.ajax.handleComplete( s, xhr, status, data );
317 // Handle memory leak in IE
318 script.onload = script.onreadystatechange = null;
319 if ( head && script.parentNode ) {
320 head.removeChild( script );
326 // Use insertBefore instead of appendChild to circumvent an IE6 bug.
327 // This arises when a base node is used (#2709 and #4378).
328 head.insertBefore( script, head.firstChild );
330 // We handle everything using the script element injection
334 var requestDone = false;
336 // Create the request object
344 // Passing null username, generates a login popup on Opera (#2865)
346 xhr.open(type, s.url, s.async, s.username, s.password);
348 xhr.open(type, s.url, s.async);
351 // Need an extra try/catch for cross domain requests in Firefox 3
353 // Set the correct header, if data is being sent
354 if ( s.data || origSettings && origSettings.contentType ) {
355 xhr.setRequestHeader("Content-Type", s.contentType);
358 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
359 if ( s.ifModified ) {
360 if ( jQuery.lastModified[s.url] ) {
361 xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
364 if ( jQuery.ajax.etag[s.url] ) {
365 xhr.setRequestHeader("If-None-Match", jQuery.ajax.etag[s.url]);
369 // Set header so the called script knows that it's an XMLHttpRequest
370 // Only send the header if it's not a remote XHR
372 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
375 // Set the Accepts header for the server, depending on the dataType
376 xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
377 s.accepts[ s.dataType ] + ", */*" :
378 s.accepts._default );
379 } catch( headerError ) {}
381 // Allow custom headers/mimetypes and early abort
382 if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
383 // Handle the global AJAX counter
384 if ( s.global && jQuery.ajax.active-- === 1 ) {
385 jQuery.event.trigger( "ajaxStop" );
388 // close opended socket
394 jQuery.ajax.triggerGlobal( s, "ajaxSend", [xhr, s] );
397 // Wait for a response to come back
398 var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
399 // The request was aborted
400 if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
401 // Opera doesn't call onreadystatechange before this point
402 // so we simulate the call
403 if ( !requestDone ) {
404 jQuery.ajax.handleComplete( s, xhr, status, data );
409 xhr.onreadystatechange = jQuery.noop;
412 // The transfer is complete and the data is available, or the request timed out
413 } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
415 xhr.onreadystatechange = jQuery.noop;
417 status = isTimeout === "timeout" ?
419 !jQuery.ajax.httpSuccess( xhr ) ?
421 s.ifModified && jQuery.ajax.httpNotModified( xhr, s.url ) ?
427 if ( status === "success" ) {
428 // Watch for, and catch, XML document parse errors
430 // process the data (runs the xml through httpData regardless of callback)
431 data = jQuery.ajax.httpData( xhr, s.dataType, s );
432 } catch( parserError ) {
433 status = "parsererror";
434 errMsg = parserError;
438 // Make sure that the request was successful or notmodified
439 if ( status === "success" || status === "notmodified" ) {
440 // JSONP handles its own success callback
442 jQuery.ajax.handleSuccess( s, xhr, status, data );
445 jQuery.ajax.handleError( s, xhr, status, errMsg );
448 // Fire the complete handlers
450 jQuery.ajax.handleComplete( s, xhr, status, data );
453 if ( isTimeout === "timeout" ) {
464 // Override the abort handler, if we can (IE doesn't allow it, but that's OK)
465 // Opera doesn't fire onreadystatechange at all on abort
467 var oldAbort = xhr.abort;
468 xhr.abort = function() {
470 oldAbort.call( xhr );
473 onreadystatechange( "abort" );
475 } catch( abortError ) {}
478 if ( s.async && s.timeout > 0 ) {
479 setTimeout(function() {
480 // Check to see if the request is still happening
481 if ( xhr && !requestDone ) {
482 onreadystatechange( "timeout" );
489 xhr.send( (type !== "GET" && s.data) || null );
491 } catch( sendError ) {
492 jQuery.ajax.handleError( s, xhr, null, e );
494 // Fire the complete handlers
495 jQuery.ajax.handleComplete( s, xhr, status, data );
498 // firefox 1.5 doesn't fire statechange for sync requests
500 onreadystatechange();
503 // return XMLHttpRequest to allow aborting the request etc.
507 // Serialize an array of form elements or a set of
508 // key/values into a query string
509 param: function( a, traditional ) {
510 var s = [], add = function( key, value ) {
511 // If value is a function, invoke it and return its value
512 value = jQuery.isFunction(value) ? value() : value;
513 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
516 // Set traditional to true for jQuery <= 1.3.2 behavior.
517 if ( traditional === undefined ) {
518 traditional = jQuery.ajaxSettings.traditional;
521 // If an array was passed in, assume that it is an array of form elements.
522 if ( jQuery.isArray(a) || a.jquery ) {
523 // Serialize the form elements
524 jQuery.each( a, function() {
525 add( this.name, this.value );
529 // If traditional, encode the "old" way (the way 1.3.2 or older
530 // did it), otherwise encode params recursively.
531 for ( var prefix in a ) {
532 buildParams( prefix, a[prefix], traditional, add );
536 // Return the resulting serialization
537 return s.join("&").replace(r20, "+");
541 function buildParams( prefix, obj, traditional, add ) {
542 if ( jQuery.isArray(obj) ) {
543 // Serialize array item.
544 jQuery.each( obj, function( i, v ) {
545 if ( traditional || /\[\]$/.test( prefix ) ) {
546 // Treat each array item as a scalar.
550 // If array item is non-scalar (array or object), encode its
551 // numeric index to resolve deserialization ambiguity issues.
552 // Note that rack (as of 1.0.0) can't currently deserialize
553 // nested arrays properly, and attempting to do so may cause
554 // a server error. Possible fixes are to modify rack's
555 // deserialization algorithm or to provide an option or flag
556 // to force array serialization to be shallow.
557 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
561 } else if ( !traditional && obj != null && typeof obj === "object" ) {
562 // Serialize object item.
563 jQuery.each( obj, function( k, v ) {
564 buildParams( prefix + "[" + k + "]", v, traditional, add );
568 // Serialize scalar item.
573 jQuery.extend( jQuery.ajax, {
575 // Counter for holding the number of active queries
578 // Last-Modified header cache for next request
582 handleError: function( s, xhr, status, e ) {
583 // If a local callback was specified, fire it
585 s.error.call( s.context, xhr, status, e );
588 // Fire the global callback
590 jQuery.ajax.triggerGlobal( s, "ajaxError", [xhr, s, e] );
594 handleSuccess: function( s, xhr, status, data ) {
595 // If a local callback was specified, fire it and pass it the data
597 s.success.call( s.context, data, status, xhr );
600 // Fire the global callback
602 jQuery.ajax.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
606 handleComplete: function( s, xhr, status ) {
609 s.complete.call( s.context, xhr, status );
612 // The request was completed
614 jQuery.ajax.triggerGlobal( s, "ajaxComplete", [xhr, s] );
617 // Handle the global AJAX counter
618 if ( s.global && jQuery.ajax.active-- === 1 ) {
619 jQuery.event.trigger( "ajaxStop" );
623 triggerGlobal: function( s, type, args ) {
624 (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
627 // Determines if an XMLHttpRequest was successful or not
628 httpSuccess: function( xhr ) {
630 // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
631 return !xhr.status && location.protocol === "file:" ||
632 ( xhr.status >= 200 && xhr.status < 300 ) ||
633 xhr.status === 304 || xhr.status === 1223 ||
634 // Opera returns a status of 0 for redirects -
635 // We can detect this by the fact that Opera also doesn't return any headers
636 xhr.status === 0 && !xhr.getAllResponseHeaders();
642 // Determines if an XMLHttpRequest returns NotModified
643 httpNotModified: function( xhr, url ) {
644 var lastModified = xhr.getResponseHeader("Last-Modified"),
645 etag = xhr.getResponseHeader("Etag");
647 if ( lastModified ) {
648 jQuery.ajax.lastModified[url] = lastModified;
652 jQuery.ajax.etag[url] = etag;
655 // Opera returns 0 when status is 304
656 return xhr.status === 304 || xhr.status === 0 && !xhr.getAllResponseHeaders();
659 httpData: function( xhr, type, s ) {
660 var ct = xhr.getResponseHeader("content-type") || "",
661 xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
662 data = xml ? xhr.responseXML : xhr.responseText;
664 if ( xml && data.documentElement.nodeName === "parsererror" ) {
665 jQuery.error( "parsererror" );
668 // Allow a pre-filtering function to sanitize the response
669 // s is checked to keep backwards compatibility
670 if ( s && s.dataFilter ) {
671 data = s.dataFilter( data, type );
674 // The filter can actually parse the response
675 if ( typeof data === "string" ) {
676 // Get the JavaScript object, if JSON is used.
677 if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
678 data = jQuery.parseJSON( data );
680 // If the type is "script", eval it in global context
681 } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
682 jQuery.globalEval( data );
691 // Does this browser support XHR requests?
692 jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
694 // For backwards compatibility
695 jQuery.extend( jQuery.ajax );