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,
7 rnoContent = /^(?:GET|HEAD)$/,
11 rts = /([?&])_=[^&]*/,
12 rurl = /^(\w+:)?\/\/([^\/?#]+)/,
16 // Keep a copy of the old load method
17 _load = jQuery.fn.load;
20 load: function( url, params, callback ) {
21 if ( typeof url !== "string" && _load ) {
22 return _load.apply( this, arguments );
24 // Don't do a request if no elements are being requested
25 } else if ( !this.length ) {
29 var off = url.indexOf(" ");
31 var selector = url.slice(off, url.length);
32 url = url.slice(0, off);
35 // Default to a GET request
38 // If the second parameter was provided
41 if ( jQuery.isFunction( params ) ) {
42 // We assume that it's the callback
46 // Otherwise, build a param string
47 } else if ( typeof params === "object" ) {
48 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
55 // Request the remote document
61 complete: function( res, status ) {
62 // If successful, inject the HTML into all the matched elements
63 if ( status === "success" || status === "notmodified" ) {
64 // See if a selector was specified
66 // Create a dummy div to hold the results
68 // inject the contents of the document in, removing the scripts
69 // to avoid any 'Permission Denied' errors in IE
70 .append(res.responseText.replace(rscript, ""))
72 // Locate the specified elements
75 // If not, just inject the full result
80 self.each( callback, [res.responseText, status, res] );
88 serialize: function() {
89 return jQuery.param(this.serializeArray());
92 serializeArray: function() {
93 return this.map(function() {
94 return this.elements ? jQuery.makeArray(this.elements) : this;
97 return this.name && !this.disabled &&
98 (this.checked || rselectTextarea.test(this.nodeName) ||
99 rinput.test(this.type));
101 .map(function( i, elem ) {
102 var val = jQuery(this).val();
106 jQuery.isArray(val) ?
107 jQuery.map( val, function( val, i ) {
108 return { name: elem.name, value: val };
110 { name: elem.name, value: val };
115 // Attach a bunch of functions for handling common AJAX events
116 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
117 jQuery.fn[o] = function( f ) {
118 return this.bind(o, f);
123 get: function( url, data, callback, type ) {
124 // shift arguments if data argument was omited
125 if ( jQuery.isFunction( data ) ) {
126 type = type || callback;
140 getScript: function( url, callback ) {
141 return jQuery.get(url, null, callback, "script");
144 getJSON: function( url, data, callback ) {
145 return jQuery.get(url, data, callback, "json");
148 post: function( url, data, callback, type ) {
149 // shift arguments if data argument was omited
150 if ( jQuery.isFunction( data ) ) {
151 type = type || callback;
165 ajaxSetup: function( settings ) {
166 jQuery.extend( jQuery.ajaxSettings, settings );
173 contentType: "application/x-www-form-urlencoded",
183 // This function can be overriden by calling jQuery.ajaxSetup
185 return new window.XMLHttpRequest();
188 xml: "application/xml, text/xml",
190 script: "text/javascript, application/javascript",
191 json: "application/json, text/javascript",
197 ajax: function( origSettings ) {
198 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
199 jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type);
201 s.url = s.url.replace( rhash, "" );
203 // Use original (not extended) context object if it was provided
204 s.context = origSettings && origSettings.context != null ? origSettings.context : s;
206 // convert data if not already a string
207 if ( s.data && s.processData && typeof s.data !== "string" ) {
208 s.data = jQuery.param( s.data, s.traditional );
211 // Handle JSONP Parameter Callbacks
212 if ( s.dataType === "jsonp" ) {
213 if ( type === "GET" ) {
214 if ( !jsre.test( s.url ) ) {
215 s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
217 } else if ( !s.data || !jsre.test(s.data) ) {
218 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
223 // Build temporary JSONP function
224 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
225 jsonp = s.jsonpCallback || ("jsonp" + jsc++);
227 // Replace the =? sequence both in the query string and the data
229 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
232 s.url = s.url.replace(jsre, "=" + jsonp + "$1");
234 // We need to make sure
235 // that a JSONP style response is executed properly
236 s.dataType = "script";
238 // Handle JSONP-style loading
239 var customJsonp = window[ jsonp ];
241 window[ jsonp ] = function( tmp ) {
242 if ( jQuery.isFunction( customJsonp ) ) {
247 window[ jsonp ] = undefined;
250 delete window[ jsonp ];
251 } catch( jsonpError ) {}
255 jQuery.handleSuccess( s, xhr, status, data );
256 jQuery.handleComplete( s, xhr, status, data );
259 head.removeChild( script );
264 if ( s.dataType === "script" && s.cache === null ) {
268 if ( s.cache === false && noContent ) {
269 var ts = jQuery.now();
271 // try replacing _= if it is there
272 var ret = s.url.replace(rts, "$1_=" + ts);
274 // if nothing was replaced, add timestamp to the end
275 s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
278 // If data is available, append data to url for GET/HEAD requests
279 if ( s.data && noContent ) {
280 s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
283 // Watch for a new set of requests
284 if ( s.global && jQuery.active++ === 0 ) {
285 jQuery.event.trigger( "ajaxStart" );
288 // Matches an absolute URL, and saves the domain
289 var parts = rurl.exec( s.url ),
290 remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host);
292 // If we're requesting a remote document
293 // and trying to load JSON or Script with a GET
294 if ( s.dataType === "script" && type === "GET" && remote ) {
295 var head = document.getElementsByTagName("head")[0] || document.documentElement;
296 var script = document.createElement("script");
297 if ( s.scriptCharset ) {
298 script.charset = s.scriptCharset;
302 // Handle Script loading
306 // Attach handlers for all browsers
307 script.onload = script.onreadystatechange = function() {
308 if ( !done && (!this.readyState ||
309 this.readyState === "loaded" || this.readyState === "complete") ) {
311 jQuery.handleSuccess( s, xhr, status, data );
312 jQuery.handleComplete( s, xhr, status, data );
314 // Handle memory leak in IE
315 script.onload = script.onreadystatechange = null;
316 if ( head && script.parentNode ) {
317 head.removeChild( script );
323 // Use insertBefore instead of appendChild to circumvent an IE6 bug.
324 // This arises when a base node is used (#2709 and #4378).
325 head.insertBefore( script, head.firstChild );
327 // We handle everything using the script element injection
331 var requestDone = false;
333 // Create the request object
341 // Passing null username, generates a login popup on Opera (#2865)
343 xhr.open(type, s.url, s.async, s.username, s.password);
345 xhr.open(type, s.url, s.async);
348 // Need an extra try/catch for cross domain requests in Firefox 3
350 // Set content-type if data specified and content-body is valid for this type
351 if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) {
352 xhr.setRequestHeader("Content-Type", s.contentType);
355 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
356 if ( s.ifModified ) {
357 if ( jQuery.lastModified[s.url] ) {
358 xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
361 if ( jQuery.etag[s.url] ) {
362 xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
366 // Set header so the called script knows that it's an XMLHttpRequest
367 // Only send the header if it's not a remote XHR
369 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
372 // Set the Accepts header for the server, depending on the dataType
373 xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
374 s.accepts[ s.dataType ] + ", */*; q=0.01" :
375 s.accepts._default );
376 } catch( headerError ) {}
378 // Allow custom headers/mimetypes and early abort
379 if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
380 // Handle the global AJAX counter
381 if ( s.global && jQuery.active-- === 1 ) {
382 jQuery.event.trigger( "ajaxStop" );
385 // close opended socket
391 jQuery.triggerGlobal( s, "ajaxSend", [xhr, s] );
394 // Wait for a response to come back
395 var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
396 // The request was aborted
397 if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
398 // Opera doesn't call onreadystatechange before this point
399 // so we simulate the call
400 if ( !requestDone ) {
401 jQuery.handleComplete( s, xhr, status, data );
406 xhr.onreadystatechange = jQuery.noop;
409 // The transfer is complete and the data is available, or the request timed out
410 } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
412 xhr.onreadystatechange = jQuery.noop;
414 status = isTimeout === "timeout" ?
416 !jQuery.httpSuccess( xhr ) ?
418 s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
424 if ( status === "success" ) {
425 // Watch for, and catch, XML document parse errors
427 // process the data (runs the xml through httpData regardless of callback)
428 data = jQuery.httpData( xhr, s.dataType, s );
429 } catch( parserError ) {
430 status = "parsererror";
431 errMsg = parserError;
435 // Make sure that the request was successful or notmodified
436 if ( status === "success" || status === "notmodified" ) {
437 // JSONP handles its own success callback
439 jQuery.handleSuccess( s, xhr, status, data );
442 jQuery.handleError( s, xhr, status, errMsg );
445 // Fire the complete handlers
447 jQuery.handleComplete( s, xhr, status, data );
450 if ( isTimeout === "timeout" ) {
461 // Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK)
462 // Opera doesn't fire onreadystatechange at all on abort
464 var oldAbort = xhr.abort;
465 xhr.abort = function() {
467 // oldAbort has no call property in IE7 so
468 // just do it this way, which works in all
470 Function.prototype.call.call( oldAbort, 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( noContent || s.data == null ? null : s.data );
491 } catch( sendError ) {
492 jQuery.handleError( s, xhr, null, sendError );
494 // Fire the complete handlers
495 jQuery.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 ) {
511 add = function( key, value ) {
512 // If value is a function, invoke it and return its value
513 value = jQuery.isFunction(value) ? value() : value;
514 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
517 // Set traditional to true for jQuery <= 1.3.2 behavior.
518 if ( traditional === undefined ) {
519 traditional = jQuery.ajaxSettings.traditional;
522 // If an array was passed in, assume that it is an array of form elements.
523 if ( jQuery.isArray(a) || a.jquery ) {
524 // Serialize the form elements
525 jQuery.each( a, function() {
526 add( this.name, this.value );
530 // If traditional, encode the "old" way (the way 1.3.2 or older
531 // did it), otherwise encode params recursively.
532 for ( var prefix in a ) {
533 buildParams( prefix, a[prefix], traditional, add );
537 // Return the resulting serialization
538 return s.join("&").replace(r20, "+");
542 function buildParams( prefix, obj, traditional, add ) {
543 if ( jQuery.isArray(obj) && obj.length ) {
544 // Serialize array item.
545 jQuery.each( obj, function( i, v ) {
546 if ( traditional || rbracket.test( prefix ) ) {
547 // Treat each array item as a scalar.
551 // If array item is non-scalar (array or object), encode its
552 // numeric index to resolve deserialization ambiguity issues.
553 // Note that rack (as of 1.0.0) can't currently deserialize
554 // nested arrays properly, and attempting to do so may cause
555 // a server error. Possible fixes are to modify rack's
556 // deserialization algorithm or to provide an option or flag
557 // to force array serialization to be shallow.
558 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
562 } else if ( !traditional && obj != null && typeof obj === "object" ) {
563 if ( jQuery.isEmptyObject( obj ) ) {
566 // Serialize object item.
568 jQuery.each( obj, function( k, v ) {
569 buildParams( prefix + "[" + k + "]", v, traditional, add );
574 // Serialize scalar item.
579 // This is still on the jQuery object... for now
580 // Want to move this to jQuery.ajax some day
583 // Counter for holding the number of active queries
586 // Last-Modified header cache for next request
590 handleError: function( s, xhr, status, e ) {
591 // If a local callback was specified, fire it
593 s.error.call( s.context, xhr, status, e );
596 // Fire the global callback
598 jQuery.triggerGlobal( s, "ajaxError", [xhr, s, e] );
602 handleSuccess: function( s, xhr, status, data ) {
603 // If a local callback was specified, fire it and pass it the data
605 s.success.call( s.context, data, status, xhr );
608 // Fire the global callback
610 jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
614 handleComplete: function( s, xhr, status ) {
617 s.complete.call( s.context, xhr, status );
620 // The request was completed
622 jQuery.triggerGlobal( s, "ajaxComplete", [xhr, s] );
625 // Handle the global AJAX counter
626 if ( s.global && jQuery.active-- === 1 ) {
627 jQuery.event.trigger( "ajaxStop" );
631 triggerGlobal: function( s, type, args ) {
632 (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
635 // Determines if an XMLHttpRequest was successful or not
636 httpSuccess: function( xhr ) {
638 // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
639 return !xhr.status && location.protocol === "file:" ||
640 xhr.status >= 200 && xhr.status < 300 ||
641 xhr.status === 304 || xhr.status === 1223;
647 // Determines if an XMLHttpRequest returns NotModified
648 httpNotModified: function( xhr, url ) {
649 var lastModified = xhr.getResponseHeader("Last-Modified"),
650 etag = xhr.getResponseHeader("Etag");
652 if ( lastModified ) {
653 jQuery.lastModified[url] = lastModified;
657 jQuery.etag[url] = etag;
660 return xhr.status === 304;
663 httpData: function( xhr, type, s ) {
664 var ct = xhr.getResponseHeader("content-type") || "",
665 xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
666 data = xml ? xhr.responseXML : xhr.responseText;
668 if ( xml && data.documentElement.nodeName === "parsererror" ) {
669 jQuery.error( "parsererror" );
672 // Allow a pre-filtering function to sanitize the response
673 // s is checked to keep backwards compatibility
674 if ( s && s.dataFilter ) {
675 data = s.dataFilter( data, type );
678 // The filter can actually parse the response
679 if ( typeof data === "string" ) {
680 // Get the JavaScript object, if JSON is used.
681 if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
682 data = jQuery.parseJSON( data );
684 // If the type is "script", eval it in global context
685 } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
686 jQuery.globalEval( data );
696 * Create the request object; Microsoft failed to properly
697 * implement the XMLHttpRequest in IE7 (can't request local files),
698 * so we use the ActiveXObject when it is available
699 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
700 * we need a fallback.
702 if ( window.ActiveXObject ) {
703 jQuery.ajaxSettings.xhr = function() {
704 if ( window.location.protocol !== "file:" ) {
706 return new window.XMLHttpRequest();
711 return new window.ActiveXObject("Microsoft.XMLHTTP");
712 } catch(activeError) {}
716 // Does this browser support XHR requests?
717 jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();