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|DELETE)$/,
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 // Create the request object; Microsoft failed to properly
184 // implement the XMLHttpRequest in IE7 (can't request local files),
185 // so we use the ActiveXObject when it is available
186 // This function can be overriden by calling jQuery.ajaxSetup
187 xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
189 return new window.XMLHttpRequest();
193 return new window.ActiveXObject("Microsoft.XMLHTTP");
197 xml: "application/xml, text/xml",
199 script: "text/javascript, application/javascript",
200 json: "application/json, text/javascript",
206 ajax: function( origSettings ) {
207 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
208 jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type);
210 s.url = s.url.replace( rhash, "" );
212 // Use original (not extended) context object if it was provided
213 s.context = origSettings && origSettings.context != null ? origSettings.context : s;
215 // convert data if not already a string
216 if ( s.data && s.processData && typeof s.data !== "string" ) {
217 s.data = jQuery.param( s.data, s.traditional );
220 // Handle JSONP Parameter Callbacks
221 if ( s.dataType === "jsonp" ) {
222 if ( type === "GET" ) {
223 if ( !jsre.test( s.url ) ) {
224 s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
226 } else if ( !s.data || !jsre.test(s.data) ) {
227 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
232 // Build temporary JSONP function
233 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
234 jsonp = s.jsonpCallback || ("jsonp" + jsc++);
236 // Replace the =? sequence both in the query string and the data
238 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
241 s.url = s.url.replace(jsre, "=" + jsonp + "$1");
243 // We need to make sure
244 // that a JSONP style response is executed properly
245 s.dataType = "script";
247 // Handle JSONP-style loading
248 var customJsonp = window[ jsonp ];
250 window[ jsonp ] = function( tmp ) {
252 jQuery.ajax.handleSuccess( s, xhr, status, data );
253 jQuery.ajax.handleComplete( s, xhr, status, data );
255 if ( jQuery.isFunction( customJsonp ) ) {
260 window[ jsonp ] = undefined;
263 delete window[ jsonp ];
264 } catch( jsonpError ) {}
268 head.removeChild( script );
273 if ( s.dataType === "script" && s.cache === null ) {
277 if ( s.cache === false && type === "GET" ) {
278 var ts = jQuery.now();
280 // try replacing _= if it is there
281 var ret = s.url.replace(rts, "$1_=" + ts);
283 // if nothing was replaced, add timestamp to the end
284 s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
287 // If data is available, append data to url for get requests
288 if ( s.data && type === "GET" ) {
289 s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
292 // Watch for a new set of requests
293 if ( s.global && jQuery.ajax.active++ === 0 ) {
294 jQuery.event.trigger( "ajaxStart" );
297 // Matches an absolute URL, and saves the domain
298 var parts = rurl.exec( s.url ),
299 remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
301 // If we're requesting a remote document
302 // and trying to load JSON or Script with a GET
303 if ( s.dataType === "script" && type === "GET" && remote ) {
304 var head = document.getElementsByTagName("head")[0] || document.documentElement;
305 var script = document.createElement("script");
306 if ( s.scriptCharset ) {
307 script.charset = s.scriptCharset;
311 // Handle Script loading
315 // Attach handlers for all browsers
316 script.onload = script.onreadystatechange = function() {
317 if ( !done && (!this.readyState ||
318 this.readyState === "loaded" || this.readyState === "complete") ) {
320 jQuery.ajax.handleSuccess( s, xhr, status, data );
321 jQuery.ajax.handleComplete( s, xhr, status, data );
323 // Handle memory leak in IE
324 script.onload = script.onreadystatechange = null;
325 if ( head && script.parentNode ) {
326 head.removeChild( script );
332 // Use insertBefore instead of appendChild to circumvent an IE6 bug.
333 // This arises when a base node is used (#2709 and #4378).
334 head.insertBefore( script, head.firstChild );
336 // We handle everything using the script element injection
340 var requestDone = false;
342 // Create the request object
350 // Passing null username, generates a login popup on Opera (#2865)
352 xhr.open(type, s.url, s.async, s.username, s.password);
354 xhr.open(type, s.url, s.async);
357 // Need an extra try/catch for cross domain requests in Firefox 3
359 // Set content-type if data specified and content-body is valid for this type
360 if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) {
361 xhr.setRequestHeader("Content-Type", s.contentType);
364 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
365 if ( s.ifModified ) {
366 if ( jQuery.lastModified[s.url] ) {
367 xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
370 if ( jQuery.ajax.etag[s.url] ) {
371 xhr.setRequestHeader("If-None-Match", jQuery.ajax.etag[s.url]);
375 // Set header so the called script knows that it's an XMLHttpRequest
376 // Only send the header if it's not a remote XHR
378 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
381 // Set the Accepts header for the server, depending on the dataType
382 xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
383 s.accepts[ s.dataType ] + ", */*; q=0.01" :
384 s.accepts._default );
385 } catch( headerError ) {}
387 // Allow custom headers/mimetypes and early abort
388 if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
389 // Handle the global AJAX counter
390 if ( s.global && jQuery.ajax.active-- === 1 ) {
391 jQuery.event.trigger( "ajaxStop" );
394 // close opended socket
400 jQuery.ajax.triggerGlobal( s, "ajaxSend", [xhr, s] );
403 // Wait for a response to come back
404 var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
405 // The request was aborted
406 if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
407 // Opera doesn't call onreadystatechange before this point
408 // so we simulate the call
409 if ( !requestDone ) {
410 jQuery.ajax.handleComplete( s, xhr, status, data );
415 xhr.onreadystatechange = jQuery.noop;
418 // The transfer is complete and the data is available, or the request timed out
419 } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
421 xhr.onreadystatechange = jQuery.noop;
423 status = isTimeout === "timeout" ?
425 !jQuery.ajax.httpSuccess( xhr ) ?
427 s.ifModified && jQuery.ajax.httpNotModified( xhr, s.url ) ?
433 if ( status === "success" ) {
434 // Watch for, and catch, XML document parse errors
436 // process the data (runs the xml through httpData regardless of callback)
437 data = jQuery.ajax.httpData( xhr, s.dataType, s );
438 } catch( parserError ) {
439 status = "parsererror";
440 errMsg = parserError;
444 // Make sure that the request was successful or notmodified
445 if ( status === "success" || status === "notmodified" ) {
446 // JSONP handles its own success callback
448 jQuery.ajax.handleSuccess( s, xhr, status, data );
451 jQuery.ajax.handleError( s, xhr, status, errMsg );
454 // Fire the complete handlers
456 jQuery.ajax.handleComplete( s, xhr, status, data );
459 if ( isTimeout === "timeout" ) {
470 // Override the abort handler, if we can (IE doesn't allow it, but that's OK)
471 // Opera doesn't fire onreadystatechange at all on abort
473 var oldAbort = xhr.abort;
474 xhr.abort = function() {
476 oldAbort.call( xhr );
479 onreadystatechange( "abort" );
481 } catch( abortError ) {}
484 if ( s.async && s.timeout > 0 ) {
485 setTimeout(function() {
486 // Check to see if the request is still happening
487 if ( xhr && !requestDone ) {
488 onreadystatechange( "timeout" );
495 xhr.send( noContent || s.data == null ? null : s.data );
497 } catch( sendError ) {
498 jQuery.ajax.handleError( s, xhr, null, sendError );
500 // Fire the complete handlers
501 jQuery.ajax.handleComplete( s, xhr, status, data );
504 // firefox 1.5 doesn't fire statechange for sync requests
506 onreadystatechange();
509 // return XMLHttpRequest to allow aborting the request etc.
513 // Serialize an array of form elements or a set of
514 // key/values into a query string
515 param: function( a, traditional ) {
516 var s = [], add = function( key, value ) {
517 // If value is a function, invoke it and return its value
518 value = jQuery.isFunction(value) ? value() : value;
519 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
522 // Set traditional to true for jQuery <= 1.3.2 behavior.
523 if ( traditional === undefined ) {
524 traditional = jQuery.ajaxSettings.traditional;
527 // If an array was passed in, assume that it is an array of form elements.
528 if ( jQuery.isArray(a) || a.jquery ) {
529 // Serialize the form elements
530 jQuery.each( a, function() {
531 add( this.name, this.value );
535 // If traditional, encode the "old" way (the way 1.3.2 or older
536 // did it), otherwise encode params recursively.
537 for ( var prefix in a ) {
538 buildParams( prefix, a[prefix], traditional, add );
542 // Return the resulting serialization
543 return s.join("&").replace(r20, "+");
547 function buildParams( prefix, obj, traditional, add ) {
548 if ( jQuery.isArray(obj) && obj.length ) {
549 // Serialize array item.
550 jQuery.each( obj, function( i, v ) {
551 if ( traditional || rbracket.test( prefix ) ) {
552 // Treat each array item as a scalar.
556 // If array item is non-scalar (array or object), encode its
557 // numeric index to resolve deserialization ambiguity issues.
558 // Note that rack (as of 1.0.0) can't currently deserialize
559 // nested arrays properly, and attempting to do so may cause
560 // a server error. Possible fixes are to modify rack's
561 // deserialization algorithm or to provide an option or flag
562 // to force array serialization to be shallow.
563 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
567 } else if ( !traditional && obj != null && typeof obj === "object" ) {
568 if ( jQuery.isEmptyObject( obj ) ) {
571 // Serialize object item.
573 jQuery.each( obj, function( k, v ) {
574 buildParams( prefix + "[" + k + "]", v, traditional, add );
579 // Serialize scalar item.
584 jQuery.extend( jQuery.ajax, {
586 // Counter for holding the number of active queries
589 // Last-Modified header cache for next request
593 handleError: function( s, xhr, status, e ) {
594 // If a local callback was specified, fire it
596 s.error.call( s.context, xhr, status, e );
599 // Fire the global callback
601 jQuery.ajax.triggerGlobal( s, "ajaxError", [xhr, s, e] );
605 handleSuccess: function( s, xhr, status, data ) {
606 // If a local callback was specified, fire it and pass it the data
608 s.success.call( s.context, data, status, xhr );
611 // Fire the global callback
613 jQuery.ajax.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
617 handleComplete: function( s, xhr, status ) {
620 s.complete.call( s.context, xhr, status );
623 // The request was completed
625 jQuery.ajax.triggerGlobal( s, "ajaxComplete", [xhr, s] );
628 // Handle the global AJAX counter
629 if ( s.global && jQuery.ajax.active-- === 1 ) {
630 jQuery.event.trigger( "ajaxStop" );
634 triggerGlobal: function( s, type, args ) {
635 (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
638 // Determines if an XMLHttpRequest was successful or not
639 httpSuccess: function( xhr ) {
641 // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
642 return !xhr.status && location.protocol === "file:" ||
643 xhr.status >= 200 && xhr.status < 300 ||
644 xhr.status === 304 || xhr.status === 1223;
650 // Determines if an XMLHttpRequest returns NotModified
651 httpNotModified: function( xhr, url ) {
652 var lastModified = xhr.getResponseHeader("Last-Modified"),
653 etag = xhr.getResponseHeader("Etag");
655 if ( lastModified ) {
656 jQuery.ajax.lastModified[url] = lastModified;
660 jQuery.ajax.etag[url] = etag;
663 return xhr.status === 304;
666 httpData: function( xhr, type, s ) {
667 var ct = xhr.getResponseHeader("content-type") || "",
668 xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
669 data = xml ? xhr.responseXML : xhr.responseText;
671 if ( xml && data.documentElement.nodeName === "parsererror" ) {
672 jQuery.error( "parsererror" );
675 // Allow a pre-filtering function to sanitize the response
676 // s is checked to keep backwards compatibility
677 if ( s && s.dataFilter ) {
678 data = s.dataFilter( data, type );
681 // The filter can actually parse the response
682 if ( typeof data === "string" ) {
683 // Get the JavaScript object, if JSON is used.
684 if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
685 data = jQuery.parseJSON( data );
687 // If the type is "script", eval it in global context
688 } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
689 jQuery.globalEval( data );
698 // Does this browser support XHR requests?
699 jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
701 // For backwards compatibility
702 jQuery.extend( jQuery.ajax );