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+:)?\/\/([^\/?#]+)/,
14 // Keep a copy of the old load method
15 _load = jQuery.fn.load;
18 load: function( url, params, callback ) {
19 if ( typeof url !== "string" && _load ) {
20 return _load.apply( this, arguments );
22 // Don't do a request if no elements are being requested
23 } else if ( !this.length ) {
27 var off = url.indexOf(" ");
29 var selector = url.slice(off, url.length);
30 url = url.slice(0, off);
33 // Default to a GET request
36 // If the second parameter was provided
39 if ( jQuery.isFunction( params ) ) {
40 // We assume that it's the callback
44 // Otherwise, build a param string
45 } else if ( typeof params === "object" ) {
46 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
53 // Request the remote document
59 complete: function( res, status ) {
60 // If successful, inject the HTML into all the matched elements
61 if ( status === "success" || status === "notmodified" ) {
62 // See if a selector was specified
64 // Create a dummy div to hold the results
66 // inject the contents of the document in, removing the scripts
67 // to avoid any 'Permission Denied' errors in IE
68 .append(res.responseText.replace(rscript, ""))
70 // Locate the specified elements
73 // If not, just inject the full result
78 self.each( callback, [res.responseText, status, res] );
86 serialize: function() {
87 return jQuery.param(this.serializeArray());
90 serializeArray: function() {
91 return this.map(function() {
92 return this.elements ? jQuery.makeArray(this.elements) : this;
95 return this.name && !this.disabled &&
96 (this.checked || rselectTextarea.test(this.nodeName) ||
97 rinput.test(this.type));
99 .map(function( i, elem ) {
100 var val = jQuery(this).val();
104 jQuery.isArray(val) ?
105 jQuery.map( val, function( val, i ) {
106 return { name: elem.name, value: val };
108 { name: elem.name, value: val };
113 // Attach a bunch of functions for handling common AJAX events
114 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
115 jQuery.fn[o] = function( f ) {
116 return this.bind(o, f);
121 get: function( url, data, callback, type ) {
122 // shift arguments if data argument was omited
123 if ( jQuery.isFunction( data ) ) {
124 type = type || callback;
138 getScript: function( url, callback ) {
139 return jQuery.get(url, null, callback, "script");
142 getJSON: function( url, data, callback ) {
143 return jQuery.get(url, data, callback, "json");
146 post: function( url, data, callback, type ) {
147 // shift arguments if data argument was omited
148 if ( jQuery.isFunction( data ) ) {
149 type = type || callback;
163 ajaxSetup: function( settings ) {
164 jQuery.extend( jQuery.ajaxSettings, settings );
171 contentType: "application/x-www-form-urlencoded",
181 // Create the request object; Microsoft failed to properly
182 // implement the XMLHttpRequest in IE7 (can't request local files),
183 // so we use the ActiveXObject when it is available
184 // This function can be overriden by calling jQuery.ajaxSetup
185 xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
187 return new window.XMLHttpRequest();
191 return new window.ActiveXObject("Microsoft.XMLHTTP");
195 xml: "application/xml, text/xml",
197 script: "text/javascript, application/javascript",
198 json: "application/json, text/javascript",
204 ajax: function( origSettings ) {
205 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
206 jsonp, status, data, type = s.type.toUpperCase();
208 s.context = origSettings && origSettings.context || s;
210 // convert data if not already a string
211 if ( s.data && s.processData && typeof s.data !== "string" ) {
212 s.data = jQuery.param( s.data, s.traditional );
215 // Handle JSONP Parameter Callbacks
216 if ( s.dataType === "jsonp" ) {
217 if ( type === "GET" ) {
218 if ( !jsre.test( s.url ) ) {
219 s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
221 } else if ( !s.data || !jsre.test(s.data) ) {
222 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
227 // Build temporary JSONP function
228 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
229 jsonp = s.jsonpCallback || ("jsonp" + jsc++);
231 // Replace the =? sequence both in the query string and the data
233 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
236 s.url = s.url.replace(jsre, "=" + jsonp + "$1");
238 // We need to make sure
239 // that a JSONP style response is executed properly
240 s.dataType = "script";
242 // Handle JSONP-style loading
243 var customJsonp = window[ jsonp ];
245 window[ jsonp ] = function( tmp ) {
247 jQuery.ajax.handleSuccess( s, xhr, status, data );
248 jQuery.ajax.handleComplete( s, xhr, status, data );
250 if ( jQuery.isFunction( customJsonp ) ) {
255 window[ jsonp ] = undefined;
258 delete window[ jsonp ];
259 } catch( jsonpError ) {}
263 head.removeChild( script );
268 if ( s.dataType === "script" && s.cache === null ) {
272 if ( s.cache === false && type === "GET" ) {
273 var ts = jQuery.now();
275 // try replacing _= if it is there
276 var ret = s.url.replace(rts, "$1_=" + ts + "$2");
278 // if nothing was replaced, add timestamp to the end
279 s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
282 // If data is available, append data to url for get requests
283 if ( s.data && type === "GET" ) {
284 s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
287 // Watch for a new set of requests
288 if ( s.global && jQuery.ajax.active++ === 0 ) {
289 jQuery.event.trigger( "ajaxStart" );
292 // Matches an absolute URL, and saves the domain
293 var parts = rurl.exec( s.url ),
294 remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
296 // If we're requesting a remote document
297 // and trying to load JSON or Script with a GET
298 if ( s.dataType === "script" && type === "GET" && remote ) {
299 var head = document.getElementsByTagName("head")[0] || document.documentElement;
300 var script = document.createElement("script");
302 if ( s.scriptCharset ) {
303 script.charset = s.scriptCharset;
306 // Handle Script loading
310 // Attach handlers for all browsers
311 script.onload = script.onreadystatechange = function() {
312 if ( !done && (!this.readyState ||
313 this.readyState === "loaded" || this.readyState === "complete") ) {
315 jQuery.ajax.handleSuccess( s, xhr, status, data );
316 jQuery.ajax.handleComplete( s, xhr, status, data );
318 // Handle memory leak in IE
319 script.onload = script.onreadystatechange = null;
320 if ( head && script.parentNode ) {
321 head.removeChild( script );
327 // Use insertBefore instead of appendChild to circumvent an IE6 bug.
328 // This arises when a base node is used (#2709 and #4378).
329 head.insertBefore( script, head.firstChild );
331 // We handle everything using the script element injection
335 var requestDone = false;
337 // Create the request object
345 // Passing null username, generates a login popup on Opera (#2865)
347 xhr.open(type, s.url, s.async, s.username, s.password);
349 xhr.open(type, s.url, s.async);
352 // Need an extra try/catch for cross domain requests in Firefox 3
354 // Set the correct header, if data is being sent
355 if ( s.data || origSettings && origSettings.contentType ) {
356 xhr.setRequestHeader("Content-Type", s.contentType);
359 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
360 if ( s.ifModified ) {
361 if ( jQuery.lastModified[s.url] ) {
362 xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
365 if ( jQuery.ajax.etag[s.url] ) {
366 xhr.setRequestHeader("If-None-Match", jQuery.ajax.etag[s.url]);
370 // Set header so the called script knows that it's an XMLHttpRequest
371 // Only send the header if it's not a remote XHR
373 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
376 // Set the Accepts header for the server, depending on the dataType
377 xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
378 s.accepts[ s.dataType ] + ", */*" :
379 s.accepts._default );
380 } catch( headerError ) {}
382 // Allow custom headers/mimetypes and early abort
383 if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
384 // Handle the global AJAX counter
385 if ( s.global && jQuery.ajax.active-- === 1 ) {
386 jQuery.event.trigger( "ajaxStop" );
389 // close opended socket
395 jQuery.ajax.triggerGlobal( s, "ajaxSend", [xhr, s] );
398 // Wait for a response to come back
399 var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
400 // The request was aborted
401 if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
402 // Opera doesn't call onreadystatechange before this point
403 // so we simulate the call
404 if ( !requestDone ) {
405 jQuery.ajax.handleComplete( s, xhr, status, data );
410 xhr.onreadystatechange = jQuery.noop;
413 // The transfer is complete and the data is available, or the request timed out
414 } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
416 xhr.onreadystatechange = jQuery.noop;
418 status = isTimeout === "timeout" ?
420 !jQuery.ajax.httpSuccess( xhr ) ?
422 s.ifModified && jQuery.ajax.httpNotModified( xhr, s.url ) ?
428 if ( status === "success" ) {
429 // Watch for, and catch, XML document parse errors
431 // process the data (runs the xml through httpData regardless of callback)
432 data = jQuery.ajax.httpData( xhr, s.dataType, s );
433 } catch( parserError ) {
434 status = "parsererror";
435 errMsg = parserError;
439 // Make sure that the request was successful or notmodified
440 if ( status === "success" || status === "notmodified" ) {
441 // JSONP handles its own success callback
443 jQuery.ajax.handleSuccess( s, xhr, status, data );
446 jQuery.ajax.handleError( s, xhr, status, errMsg );
449 // Fire the complete handlers
451 jQuery.ajax.handleComplete( s, xhr, status, data );
454 if ( isTimeout === "timeout" ) {
465 // Override the abort handler, if we can (IE doesn't allow it, but that's OK)
466 // Opera doesn't fire onreadystatechange at all on abort
468 var oldAbort = xhr.abort;
469 xhr.abort = function() {
471 oldAbort.call( xhr );
474 onreadystatechange( "abort" );
476 } catch( abortError ) {}
479 if ( s.async && s.timeout > 0 ) {
480 setTimeout(function() {
481 // Check to see if the request is still happening
482 if ( xhr && !requestDone ) {
483 onreadystatechange( "timeout" );
490 xhr.send( (type !== "GET" && s.data) || null );
492 } catch( sendError ) {
493 jQuery.ajax.handleError( s, xhr, null, e );
495 // Fire the complete handlers
496 jQuery.ajax.handleComplete( s, xhr, status, data );
499 // firefox 1.5 doesn't fire statechange for sync requests
501 onreadystatechange();
504 // return XMLHttpRequest to allow aborting the request etc.
508 // Serialize an array of form elements or a set of
509 // key/values into a query string
510 param: function( a, traditional ) {
511 var s = [], 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) ) {
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 // Serialize object item.
564 jQuery.each( obj, function( k, v ) {
565 buildParams( prefix + "[" + k + "]", v, traditional, add );
569 // Serialize scalar item.
574 jQuery.extend( jQuery.ajax, {
576 // Counter for holding the number of active queries
579 // Last-Modified header cache for next request
583 handleError: function( s, xhr, status, e ) {
584 // If a local callback was specified, fire it
586 s.error.call( s.context, xhr, status, e );
589 // Fire the global callback
591 jQuery.ajax.triggerGlobal( s, "ajaxError", [xhr, s, e] );
595 handleSuccess: function( s, xhr, status, data ) {
596 // If a local callback was specified, fire it and pass it the data
598 s.success.call( s.context, data, status, xhr );
601 // Fire the global callback
603 jQuery.ajax.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
607 handleComplete: function( s, xhr, status ) {
610 s.complete.call( s.context, xhr, status );
613 // The request was completed
615 jQuery.ajax.triggerGlobal( s, "ajaxComplete", [xhr, s] );
618 // Handle the global AJAX counter
619 if ( s.global && jQuery.ajax.active-- === 1 ) {
620 jQuery.event.trigger( "ajaxStop" );
624 triggerGlobal: function( s, type, args ) {
625 (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
628 // Determines if an XMLHttpRequest was successful or not
629 httpSuccess: function( xhr ) {
631 // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
632 return !xhr.status && location.protocol === "file:" ||
633 xhr.status >= 200 && xhr.status < 300 ||
634 xhr.status === 304 || xhr.status === 1223;
640 // Determines if an XMLHttpRequest returns NotModified
641 httpNotModified: function( xhr, url ) {
642 var lastModified = xhr.getResponseHeader("Last-Modified"),
643 etag = xhr.getResponseHeader("Etag");
645 if ( lastModified ) {
646 jQuery.ajax.lastModified[url] = lastModified;
650 jQuery.ajax.etag[url] = etag;
653 return xhr.status === 304;
656 httpData: function( xhr, type, s ) {
657 var ct = xhr.getResponseHeader("content-type") || "",
658 xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
659 data = xml ? xhr.responseXML : xhr.responseText;
661 if ( xml && data.documentElement.nodeName === "parsererror" ) {
662 jQuery.error( "parsererror" );
665 // Allow a pre-filtering function to sanitize the response
666 // s is checked to keep backwards compatibility
667 if ( s && s.dataFilter ) {
668 data = s.dataFilter( data, type );
671 // The filter can actually parse the response
672 if ( typeof data === "string" ) {
673 // Get the JavaScript object, if JSON is used.
674 if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
675 data = jQuery.parseJSON( data );
677 // If the type is "script", eval it in global context
678 } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
679 jQuery.globalEval( data );
688 // Does this browser support XHR requests?
689 jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
691 // For backwards compatibility
692 jQuery.extend( jQuery.ajax );