3 var jsc = jQuery.now(),
4 rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/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,
10 rts = /([?&])_=[^&]*(&?)/,
11 rurl = /^(\w+:)?\/\/([^\/?#]+)/,
15 // Keep a copy of the old load method
16 _load = jQuery.fn.load;
19 load: function( url, params, callback ) {
20 if ( typeof url !== "string" && _load ) {
21 return _load.apply( this, arguments );
23 // Don't do a request if no elements are being requested
24 } else if ( !this.length ) {
28 var off = url.indexOf(" ");
30 var selector = url.slice(off, url.length);
31 url = url.slice(0, off);
34 // Default to a GET request
37 // If the second parameter was provided
40 if ( jQuery.isFunction( params ) ) {
41 // We assume that it's the callback
45 // Otherwise, build a param string
46 } else if ( typeof params === "object" ) {
47 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
54 // Request the remote document
60 complete: function( res, status ) {
61 // If successful, inject the HTML into all the matched elements
62 if ( status === "success" || status === "notmodified" ) {
63 // See if a selector was specified
65 // Create a dummy div to hold the results
67 // inject the contents of the document in, removing the scripts
68 // to avoid any 'Permission Denied' errors in IE
69 .append(res.responseText.replace(rscript, ""))
71 // Locate the specified elements
74 // If not, just inject the full result
79 self.each( callback, [res.responseText, status, res] );
87 serialize: function() {
88 return jQuery.param(this.serializeArray());
91 serializeArray: function() {
92 return this.map(function() {
93 return this.elements ? jQuery.makeArray(this.elements) : this;
96 return this.name && !this.disabled &&
97 (this.checked || rselectTextarea.test(this.nodeName) ||
98 rinput.test(this.type));
100 .map(function( i, elem ) {
101 var val = jQuery(this).val();
105 jQuery.isArray(val) ?
106 jQuery.map( val, function( val, i ) {
107 return { name: elem.name, value: val };
109 { name: elem.name, value: val };
114 // Attach a bunch of functions for handling common AJAX events
115 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
116 jQuery.fn[o] = function( f ) {
117 return this.bind(o, f);
122 get: function( url, data, callback, type ) {
123 // shift arguments if data argument was omited
124 if ( jQuery.isFunction( data ) ) {
125 type = type || callback;
139 getScript: function( url, callback ) {
140 return jQuery.get(url, null, callback, "script");
143 getJSON: function( url, data, callback ) {
144 return jQuery.get(url, data, callback, "json");
147 post: function( url, data, callback, type ) {
148 // shift arguments if data argument was omited
149 if ( jQuery.isFunction( data ) ) {
150 type = type || callback;
164 ajaxSetup: function( settings ) {
165 jQuery.extend( jQuery.ajaxSettings, settings );
172 contentType: "application/x-www-form-urlencoded",
182 // Create the request object; Microsoft failed to properly
183 // implement the XMLHttpRequest in IE7 (can't request local files),
184 // so we use the ActiveXObject when it is available
185 // This function can be overriden by calling jQuery.ajaxSetup
186 xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
188 return new window.XMLHttpRequest();
192 return new window.ActiveXObject("Microsoft.XMLHTTP");
196 xml: "application/xml, text/xml",
198 script: "text/javascript, application/javascript",
199 json: "application/json, text/javascript",
205 ajax: function( origSettings ) {
206 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
207 jsonp, status, data, type = s.type.toUpperCase();
209 s.url = s.url.replace( rhash, "" );
210 s.context = origSettings && origSettings.context || s;
212 // convert data if not already a string
213 if ( s.data && s.processData && typeof s.data !== "string" ) {
214 s.data = jQuery.param( s.data, s.traditional );
217 // Handle JSONP Parameter Callbacks
218 if ( s.dataType === "jsonp" ) {
219 if ( type === "GET" ) {
220 if ( !jsre.test( s.url ) ) {
221 s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
223 } else if ( !s.data || !jsre.test(s.data) ) {
224 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
229 // Build temporary JSONP function
230 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
231 jsonp = s.jsonpCallback || ("jsonp" + jsc++);
233 // Replace the =? sequence both in the query string and the data
235 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
238 s.url = s.url.replace(jsre, "=" + jsonp + "$1");
240 // We need to make sure
241 // that a JSONP style response is executed properly
242 s.dataType = "script";
244 // Handle JSONP-style loading
245 var customJsonp = window[ jsonp ];
247 window[ jsonp ] = function( tmp ) {
249 jQuery.ajax.handleSuccess( s, xhr, status, data );
250 jQuery.ajax.handleComplete( s, xhr, status, data );
252 if ( jQuery.isFunction( customJsonp ) ) {
257 window[ jsonp ] = undefined;
260 delete window[ jsonp ];
261 } catch( jsonpError ) {}
265 head.removeChild( script );
270 if ( s.dataType === "script" && s.cache === null ) {
274 if ( s.cache === false && type === "GET" ) {
275 var ts = jQuery.now();
277 // try replacing _= if it is there
278 var ret = s.url.replace(rts, "$1_=" + ts + "$2");
280 // if nothing was replaced, add timestamp to the end
281 s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
284 // If data is available, append data to url for get requests
285 if ( s.data && type === "GET" ) {
286 s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
289 // Watch for a new set of requests
290 if ( s.global && jQuery.ajax.active++ === 0 ) {
291 jQuery.event.trigger( "ajaxStart" );
294 // Matches an absolute URL, and saves the domain
295 var parts = rurl.exec( s.url ),
296 remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
298 // If we're requesting a remote document
299 // and trying to load JSON or Script with a GET
300 if ( s.dataType === "script" && type === "GET" && remote ) {
301 var head = document.getElementsByTagName("head")[0] || document.documentElement;
302 var script = document.createElement("script");
304 if ( s.scriptCharset ) {
305 script.charset = s.scriptCharset;
308 // Handle Script loading
312 // Attach handlers for all browsers
313 script.onload = script.onreadystatechange = function() {
314 if ( !done && (!this.readyState ||
315 this.readyState === "loaded" || this.readyState === "complete") ) {
317 jQuery.ajax.handleSuccess( s, xhr, status, data );
318 jQuery.ajax.handleComplete( s, xhr, status, data );
320 // Handle memory leak in IE
321 script.onload = script.onreadystatechange = null;
322 if ( head && script.parentNode ) {
323 head.removeChild( script );
329 // Use insertBefore instead of appendChild to circumvent an IE6 bug.
330 // This arises when a base node is used (#2709 and #4378).
331 head.insertBefore( script, head.firstChild );
333 // We handle everything using the script element injection
337 var requestDone = false;
339 // Create the request object
347 // Passing null username, generates a login popup on Opera (#2865)
349 xhr.open(type, s.url, s.async, s.username, s.password);
351 xhr.open(type, s.url, s.async);
354 // Need an extra try/catch for cross domain requests in Firefox 3
356 // Set the correct header, if data is being sent
357 if ( s.data || origSettings && origSettings.contentType ) {
358 xhr.setRequestHeader("Content-Type", s.contentType);
361 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
362 if ( s.ifModified ) {
363 if ( jQuery.lastModified[s.url] ) {
364 xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
367 if ( jQuery.ajax.etag[s.url] ) {
368 xhr.setRequestHeader("If-None-Match", jQuery.ajax.etag[s.url]);
372 // Set header so the called script knows that it's an XMLHttpRequest
373 // Only send the header if it's not a remote XHR
375 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
378 // Set the Accepts header for the server, depending on the dataType
379 xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
380 s.accepts[ s.dataType ] + ", */*" :
381 s.accepts._default );
382 } catch( headerError ) {}
384 // Allow custom headers/mimetypes and early abort
385 if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
386 // Handle the global AJAX counter
387 if ( s.global && jQuery.ajax.active-- === 1 ) {
388 jQuery.event.trigger( "ajaxStop" );
391 // close opended socket
397 jQuery.ajax.triggerGlobal( s, "ajaxSend", [xhr, s] );
400 // Wait for a response to come back
401 var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
402 // The request was aborted
403 if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
404 // Opera doesn't call onreadystatechange before this point
405 // so we simulate the call
406 if ( !requestDone ) {
407 jQuery.ajax.handleComplete( s, xhr, status, data );
412 xhr.onreadystatechange = jQuery.noop;
415 // The transfer is complete and the data is available, or the request timed out
416 } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
418 xhr.onreadystatechange = jQuery.noop;
420 status = isTimeout === "timeout" ?
422 !jQuery.ajax.httpSuccess( xhr ) ?
424 s.ifModified && jQuery.ajax.httpNotModified( xhr, s.url ) ?
430 if ( status === "success" ) {
431 // Watch for, and catch, XML document parse errors
433 // process the data (runs the xml through httpData regardless of callback)
434 data = jQuery.ajax.httpData( xhr, s.dataType, s );
435 } catch( parserError ) {
436 status = "parsererror";
437 errMsg = parserError;
441 // Make sure that the request was successful or notmodified
442 if ( status === "success" || status === "notmodified" ) {
443 // JSONP handles its own success callback
445 jQuery.ajax.handleSuccess( s, xhr, status, data );
448 jQuery.ajax.handleError( s, xhr, status, errMsg );
451 // Fire the complete handlers
453 jQuery.ajax.handleComplete( s, xhr, status, data );
456 if ( isTimeout === "timeout" ) {
467 // Override the abort handler, if we can (IE doesn't allow it, but that's OK)
468 // Opera doesn't fire onreadystatechange at all on abort
470 var oldAbort = xhr.abort;
471 xhr.abort = function() {
473 oldAbort.call( xhr );
476 onreadystatechange( "abort" );
478 } catch( abortError ) {}
481 if ( s.async && s.timeout > 0 ) {
482 setTimeout(function() {
483 // Check to see if the request is still happening
484 if ( xhr && !requestDone ) {
485 onreadystatechange( "timeout" );
492 xhr.send( (type !== "GET" && s.data) || null );
494 } catch( sendError ) {
495 jQuery.ajax.handleError( s, xhr, null, e );
497 // Fire the complete handlers
498 jQuery.ajax.handleComplete( s, xhr, status, data );
501 // firefox 1.5 doesn't fire statechange for sync requests
503 onreadystatechange();
506 // return XMLHttpRequest to allow aborting the request etc.
510 // Serialize an array of form elements or a set of
511 // key/values into a query string
512 param: function( a, traditional ) {
513 var s = [], add = function( key, value ) {
514 // If value is a function, invoke it and return its value
515 value = jQuery.isFunction(value) ? value() : value;
516 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
519 // Set traditional to true for jQuery <= 1.3.2 behavior.
520 if ( traditional === undefined ) {
521 traditional = jQuery.ajaxSettings.traditional;
524 // If an array was passed in, assume that it is an array of form elements.
525 if ( jQuery.isArray(a) || a.jquery ) {
526 // Serialize the form elements
527 jQuery.each( a, function() {
528 add( this.name, this.value );
532 // If traditional, encode the "old" way (the way 1.3.2 or older
533 // did it), otherwise encode params recursively.
534 for ( var prefix in a ) {
535 buildParams( prefix, a[prefix], traditional, add );
539 // Return the resulting serialization
540 return s.join("&").replace(r20, "+");
544 function buildParams( prefix, obj, traditional, add ) {
545 if ( jQuery.isArray(obj) ) {
546 // Serialize array item.
547 jQuery.each( obj, function( i, v ) {
548 if ( traditional || rbracket.test( prefix ) ) {
549 // Treat each array item as a scalar.
553 // If array item is non-scalar (array or object), encode its
554 // numeric index to resolve deserialization ambiguity issues.
555 // Note that rack (as of 1.0.0) can't currently deserialize
556 // nested arrays properly, and attempting to do so may cause
557 // a server error. Possible fixes are to modify rack's
558 // deserialization algorithm or to provide an option or flag
559 // to force array serialization to be shallow.
560 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
564 } else if ( !traditional && obj != null && typeof obj === "object" ) {
565 // Serialize object item.
566 jQuery.each( obj, function( k, v ) {
567 buildParams( prefix + "[" + k + "]", v, traditional, add );
571 // Serialize scalar item.
576 jQuery.extend( jQuery.ajax, {
578 // Counter for holding the number of active queries
581 // Last-Modified header cache for next request
585 handleError: function( s, xhr, status, e ) {
586 // If a local callback was specified, fire it
588 s.error.call( s.context, xhr, status, e );
591 // Fire the global callback
593 jQuery.ajax.triggerGlobal( s, "ajaxError", [xhr, s, e] );
597 handleSuccess: function( s, xhr, status, data ) {
598 // If a local callback was specified, fire it and pass it the data
600 s.success.call( s.context, data, status, xhr );
603 // Fire the global callback
605 jQuery.ajax.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
609 handleComplete: function( s, xhr, status ) {
612 s.complete.call( s.context, xhr, status );
615 // The request was completed
617 jQuery.ajax.triggerGlobal( s, "ajaxComplete", [xhr, s] );
620 // Handle the global AJAX counter
621 if ( s.global && jQuery.ajax.active-- === 1 ) {
622 jQuery.event.trigger( "ajaxStop" );
626 triggerGlobal: function( s, type, args ) {
627 (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
630 // Determines if an XMLHttpRequest was successful or not
631 httpSuccess: function( xhr ) {
633 // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
634 return !xhr.status && location.protocol === "file:" ||
635 xhr.status >= 200 && xhr.status < 300 ||
636 xhr.status === 304 || xhr.status === 1223;
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 return xhr.status === 304;
658 httpData: function( xhr, type, s ) {
659 var ct = xhr.getResponseHeader("content-type") || "",
660 xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
661 data = xml ? xhr.responseXML : xhr.responseText;
663 if ( xml && data.documentElement.nodeName === "parsererror" ) {
664 jQuery.error( "parsererror" );
667 // Allow a pre-filtering function to sanitize the response
668 // s is checked to keep backwards compatibility
669 if ( s && s.dataFilter ) {
670 data = s.dataFilter( data, type );
673 // The filter can actually parse the response
674 if ( typeof data === "string" ) {
675 // Get the JavaScript object, if JSON is used.
676 if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
677 data = jQuery.parseJSON( data );
679 // If the type is "script", eval it in global context
680 } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
681 jQuery.globalEval( data );
690 // Does this browser support XHR requests?
691 jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
693 // For backwards compatibility
694 jQuery.extend( jQuery.ajax );