1 var jsc = jQuery.now(),
2 rscript = /<script(.|\s)*?\/script>/gi,
3 rselectTextarea = /select|textarea/i,
4 rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,
7 rts = /(\?|&)_=.*?(&|$)/,
8 rurl = /^(\w+:)?\/\/([^\/?#]+)/,
11 // Keep a copy of the old load method
12 _load = jQuery.fn.load;
15 load: function( url, params, callback ) {
16 if ( typeof url !== "string" && _load ) {
17 return _load.apply( this, arguments );
19 // Don't do a request if no elements are being requested
20 } else if ( !this.length ) {
24 var off = url.indexOf(" ");
26 var selector = url.slice(off, url.length);
27 url = url.slice(0, off);
30 // Default to a GET request
33 // If the second parameter was provided
36 if ( jQuery.isFunction( params ) ) {
37 // We assume that it's the callback
41 // Otherwise, build a param string
42 } else if ( typeof params === "object" ) {
43 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
50 // Request the remote document
56 complete: function( res, status ) {
57 // If successful, inject the HTML into all the matched elements
58 if ( status === "success" || status === "notmodified" ) {
59 // See if a selector was specified
61 // Create a dummy div to hold the results
63 // inject the contents of the document in, removing the scripts
64 // to avoid any 'Permission Denied' errors in IE
65 .append(res.responseText.replace(rscript, ""))
67 // Locate the specified elements
70 // If not, just inject the full result
75 self.each( callback, [res.responseText, status, res] );
83 serialize: function() {
84 return jQuery.param(this.serializeArray());
87 serializeArray: function() {
88 return this.map(function() {
89 return this.elements ? jQuery.makeArray(this.elements) : this;
92 return this.name && !this.disabled &&
93 (this.checked || rselectTextarea.test(this.nodeName) ||
94 rinput.test(this.type));
96 .map(function( i, elem ) {
97 var val = jQuery(this).val();
101 jQuery.isArray(val) ?
102 jQuery.map( val, function( val, i ) {
103 return { name: elem.name, value: val };
105 { name: elem.name, value: val };
110 // Attach a bunch of functions for handling common AJAX events
111 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
112 jQuery.fn[o] = function( f ) {
113 return this.bind(o, f);
118 get: function( url, data, callback, type ) {
119 // shift arguments if data argument was omited
120 if ( jQuery.isFunction( data ) ) {
121 type = type || callback;
135 getScript: function( url, callback ) {
136 return jQuery.get(url, null, callback, "script");
139 getJSON: function( url, data, callback ) {
140 return jQuery.get(url, data, callback, "json");
143 post: function( url, data, callback, type ) {
144 // shift arguments if data argument was omited
145 if ( jQuery.isFunction( data ) ) {
146 type = type || callback;
160 ajaxSetup: function( settings ) {
161 jQuery.extend( jQuery.ajaxSettings, settings );
168 contentType: "application/x-www-form-urlencoded",
178 // Create the request object; Microsoft failed to properly
179 // implement the XMLHttpRequest in IE7 (can't request local files),
180 // so we use the ActiveXObject when it is available
181 // This function can be overriden by calling jQuery.ajaxSetup
182 xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
184 return new window.XMLHttpRequest();
188 return new window.ActiveXObject("Microsoft.XMLHTTP");
192 xml: "application/xml, text/xml",
194 script: "text/javascript, application/javascript",
195 json: "application/json, text/javascript",
201 ajax: function( origSettings ) {
202 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
203 jsonp, status, data, type = s.type.toUpperCase();
205 s.context = origSettings && origSettings.context || s;
207 // convert data if not already a string
208 if ( s.data && s.processData && typeof s.data !== "string" ) {
209 s.data = jQuery.param( s.data, s.traditional );
212 // Handle JSONP Parameter Callbacks
213 if ( s.dataType === "jsonp" ) {
214 if ( type === "GET" ) {
215 if ( !jsre.test( s.url ) ) {
216 s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
218 } else if ( !s.data || !jsre.test(s.data) ) {
219 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
224 // Build temporary JSONP function
225 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
226 jsonp = s.jsonpCallback || ("jsonp" + jsc++);
228 // Replace the =? sequence both in the query string and the data
230 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
233 s.url = s.url.replace(jsre, "=" + jsonp + "$1");
235 // We need to make sure
236 // that a JSONP style response is executed properly
237 s.dataType = "script";
239 // Handle JSONP-style loading
240 window[ jsonp ] = window[ jsonp ] || function( tmp ) {
242 jQuery.ajax.handleSuccess( s, xhr, status, data );
243 jQuery.ajax.handleComplete( s, xhr, status, data );
245 window[ jsonp ] = undefined;
248 delete window[ jsonp ];
249 } catch( jsonpError ) {}
252 head.removeChild( script );
257 if ( s.dataType === "script" && s.cache === null ) {
261 if ( s.cache === false && type === "GET" ) {
262 var ts = jQuery.now();
264 // try replacing _= if it is there
265 var ret = s.url.replace(rts, "$1_=" + ts + "$2");
267 // if nothing was replaced, add timestamp to the end
268 s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
271 // If data is available, append data to url for get requests
272 if ( s.data && type === "GET" ) {
273 s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
276 // Watch for a new set of requests
277 if ( s.global && jQuery.ajax.active++ === 0 ) {
278 jQuery.event.trigger( "ajaxStart" );
281 // Matches an absolute URL, and saves the domain
282 var parts = rurl.exec( s.url ),
283 remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
285 // If we're requesting a remote document
286 // and trying to load JSON or Script with a GET
287 if ( s.dataType === "script" && type === "GET" && remote ) {
288 var head = document.getElementsByTagName("head")[0] || document.documentElement;
289 var script = document.createElement("script");
291 if ( s.scriptCharset ) {
292 script.charset = s.scriptCharset;
295 // Handle Script loading
299 // Attach handlers for all browsers
300 script.onload = script.onreadystatechange = function() {
301 if ( !done && (!this.readyState ||
302 this.readyState === "loaded" || this.readyState === "complete") ) {
304 jQuery.ajax.handleSuccess( s, xhr, status, data );
305 jQuery.ajax.handleComplete( s, xhr, status, data );
307 // Handle memory leak in IE
308 script.onload = script.onreadystatechange = null;
309 if ( head && script.parentNode ) {
310 head.removeChild( script );
316 // Use insertBefore instead of appendChild to circumvent an IE6 bug.
317 // This arises when a base node is used (#2709 and #4378).
318 head.insertBefore( script, head.firstChild );
320 // We handle everything using the script element injection
324 var requestDone = false;
326 // Create the request object
334 // Passing null username, generates a login popup on Opera (#2865)
336 xhr.open(type, s.url, s.async, s.username, s.password);
338 xhr.open(type, s.url, s.async);
341 // Need an extra try/catch for cross domain requests in Firefox 3
343 // Set the correct header, if data is being sent
344 if ( s.data || origSettings && origSettings.contentType ) {
345 xhr.setRequestHeader("Content-Type", s.contentType);
348 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
349 if ( s.ifModified ) {
350 if ( jQuery.lastModified[s.url] ) {
351 xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
354 if ( jQuery.ajax.etag[s.url] ) {
355 xhr.setRequestHeader("If-None-Match", jQuery.ajax.etag[s.url]);
359 // Set header so the called script knows that it's an XMLHttpRequest
360 // Only send the header if it's not a remote XHR
362 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
365 // Set the Accepts header for the server, depending on the dataType
366 xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
367 s.accepts[ s.dataType ] + ", */*" :
368 s.accepts._default );
369 } catch( headerError ) {}
371 // Allow custom headers/mimetypes and early abort
372 if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
373 // Handle the global AJAX counter
374 if ( s.global && jQuery.ajax.active-- === 1 ) {
375 jQuery.event.trigger( "ajaxStop" );
378 // close opended socket
384 jQuery.ajax.triggerGlobal( s, "ajaxSend", [xhr, s] );
387 // Wait for a response to come back
388 var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
389 // The request was aborted
390 if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
391 // Opera doesn't call onreadystatechange before this point
392 // so we simulate the call
393 if ( !requestDone ) {
394 jQuery.ajax.handleComplete( s, xhr, status, data );
399 xhr.onreadystatechange = jQuery.noop;
402 // The transfer is complete and the data is available, or the request timed out
403 } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
405 xhr.onreadystatechange = jQuery.noop;
407 status = isTimeout === "timeout" ?
409 !jQuery.ajax.httpSuccess( xhr ) ?
411 s.ifModified && jQuery.ajax.httpNotModified( xhr, s.url ) ?
417 if ( status === "success" ) {
418 // Watch for, and catch, XML document parse errors
420 // process the data (runs the xml through httpData regardless of callback)
421 data = jQuery.ajax.httpData( xhr, s.dataType, s );
422 } catch( parserError ) {
423 status = "parsererror";
424 errMsg = parserError;
428 // Make sure that the request was successful or notmodified
429 if ( status === "success" || status === "notmodified" ) {
430 // JSONP handles its own success callback
432 jQuery.ajax.handleSuccess( s, xhr, status, data );
435 jQuery.ajax.handleError( s, xhr, status, errMsg );
438 // Fire the complete handlers
439 jQuery.ajax.handleComplete( s, xhr, status, data );
441 if ( isTimeout === "timeout" ) {
452 // Override the abort handler, if we can (IE doesn't allow it, but that's OK)
453 // Opera doesn't fire onreadystatechange at all on abort
455 var oldAbort = xhr.abort;
456 xhr.abort = function() {
458 oldAbort.call( xhr );
461 onreadystatechange( "abort" );
463 } catch( abortError ) {}
466 if ( s.async && s.timeout > 0 ) {
467 setTimeout(function() {
468 // Check to see if the request is still happening
469 if ( xhr && !requestDone ) {
470 onreadystatechange( "timeout" );
477 xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null );
479 } catch( sendError ) {
480 jQuery.ajax.handleError( s, xhr, null, e );
482 // Fire the complete handlers
483 jQuery.ajax.handleComplete( s, xhr, status, data );
486 // firefox 1.5 doesn't fire statechange for sync requests
488 onreadystatechange();
491 // return XMLHttpRequest to allow aborting the request etc.
495 // Serialize an array of form elements or a set of
496 // key/values into a query string
497 param: function( a, traditional ) {
498 var s = [], add = function( key, value ) {
499 // If value is a function, invoke it and return its value
500 value = jQuery.isFunction(value) ? value() : value;
501 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
504 // Set traditional to true for jQuery <= 1.3.2 behavior.
505 if ( traditional === undefined ) {
506 traditional = jQuery.ajaxSettings.traditional;
509 // If an array was passed in, assume that it is an array of form elements.
510 if ( jQuery.isArray(a) || a.jquery ) {
511 // Serialize the form elements
512 jQuery.each( a, function() {
513 add( this.name, this.value );
517 // If traditional, encode the "old" way (the way 1.3.2 or older
518 // did it), otherwise encode params recursively.
519 for ( var prefix in a ) {
520 buildParams( prefix, a[prefix], traditional, add );
524 // Return the resulting serialization
525 return s.join("&").replace(r20, "+");
529 function buildParams( prefix, obj, traditional, add ) {
530 if ( jQuery.isArray(obj) ) {
531 // Serialize array item.
532 jQuery.each( obj, function( i, v ) {
533 if ( traditional || /\[\]$/.test( prefix ) ) {
534 // Treat each array item as a scalar.
538 // If array item is non-scalar (array or object), encode its
539 // numeric index to resolve deserialization ambiguity issues.
540 // Note that rack (as of 1.0.0) can't currently deserialize
541 // nested arrays properly, and attempting to do so may cause
542 // a server error. Possible fixes are to modify rack's
543 // deserialization algorithm or to provide an option or flag
544 // to force array serialization to be shallow.
545 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
549 } else if ( !traditional && obj != null && typeof obj === "object" ) {
550 // Serialize object item.
551 jQuery.each( obj, function( k, v ) {
552 buildParams( prefix + "[" + k + "]", v, traditional, add );
556 // Serialize scalar item.
561 jQuery.extend( jQuery.ajax, {
563 // Counter for holding the number of active queries
566 // Last-Modified header cache for next request
570 handleError: function( s, xhr, status, e ) {
571 // If a local callback was specified, fire it
573 s.error.call( s.context, xhr, status, e );
576 // Fire the global callback
578 jQuery.ajax.triggerGlobal( s, "ajaxError", [xhr, s, e] );
582 handleSuccess: function( s, xhr, status, data ) {
583 // If a local callback was specified, fire it and pass it the data
585 s.success.call( s.context, data, status, xhr );
588 // Fire the global callback
590 jQuery.ajax.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
594 handleComplete: function( s, xhr, status ) {
597 s.complete.call( s.context, xhr, status );
600 // The request was completed
602 jQuery.ajax.triggerGlobal( s, "ajaxComplete", [xhr, s] );
605 // Handle the global AJAX counter
606 if ( s.global && jQuery.ajax.active-- === 1 ) {
607 jQuery.event.trigger( "ajaxStop" );
611 triggerGlobal: function( s, type, args ) {
612 (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
615 // Determines if an XMLHttpRequest was successful or not
616 httpSuccess: function( xhr ) {
618 // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
619 return !xhr.status && location.protocol === "file:" ||
620 // Opera returns 0 when status is 304
621 ( xhr.status >= 200 && xhr.status < 300 ) ||
622 xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
628 // Determines if an XMLHttpRequest returns NotModified
629 httpNotModified: function( xhr, url ) {
630 var lastModified = xhr.getResponseHeader("Last-Modified"),
631 etag = xhr.getResponseHeader("Etag");
633 if ( lastModified ) {
634 jQuery.ajax.lastModified[url] = lastModified;
638 jQuery.ajax.etag[url] = etag;
641 // Opera returns 0 when status is 304
642 return xhr.status === 304 || xhr.status === 0;
645 httpData: function( xhr, type, s ) {
646 var ct = xhr.getResponseHeader("content-type") || "",
647 xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
648 data = xml ? xhr.responseXML : xhr.responseText;
650 if ( xml && data.documentElement.nodeName === "parsererror" ) {
651 jQuery.error( "parsererror" );
654 // Allow a pre-filtering function to sanitize the response
655 // s is checked to keep backwards compatibility
656 if ( s && s.dataFilter ) {
657 data = s.dataFilter( data, type );
660 // The filter can actually parse the response
661 if ( typeof data === "string" ) {
662 // Get the JavaScript object, if JSON is used.
663 if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
664 data = jQuery.parseJSON( data );
666 // If the type is "script", eval it in global context
667 } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
668 jQuery.globalEval( data );
677 // For backwards compatibility
678 jQuery.extend( jQuery.ajax );