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+:)?\/\/([^\/?#]+)/,
12 // Keep a copy of the old load
13 _load: jQuery.fn.load,
15 load: function( url, params, callback ) {
16 if ( typeof url !== "string" ) {
17 return this._load( url );
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 );
48 // Request the remote document
55 complete: function( res, status ) {
56 // If successful, inject the HTML into all the matched elements
57 if ( status === "success" || status === "notmodified" ) {
58 // See if a selector was specified
60 // Create a dummy div to hold the results
62 // inject the contents of the document in, removing the scripts
63 // to avoid any 'Permission Denied' errors in IE
64 .append(res.responseText.replace(rscript, ""))
66 // Locate the specified elements
69 // If not, just inject the full result
74 this.each( callback, [res.responseText, status, res] );
82 serialize: function() {
83 return jQuery.param(this.serializeArray());
85 serializeArray: function() {
86 return this.map(function() {
87 return this.elements ? jQuery.makeArray(this.elements) : this;
90 return this.name && !this.disabled &&
91 (this.checked || rselectTextarea.test(this.nodeName) ||
92 rinput.test(this.type));
94 .map(function( i, elem ) {
95 var val = jQuery(this).val();
100 jQuery.map( val, function( val, i ) {
101 return { name: elem.name, value: val };
103 { name: elem.name, value: val };
108 // Attach a bunch of functions for handling common AJAX events
109 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
110 jQuery.fn[o] = function( f ) {
111 return this.bind(o, f);
117 get: function( url, data, callback, type ) {
118 // shift arguments if data argument was omited
119 if ( jQuery.isFunction( data ) ) {
120 type = type || callback;
134 getScript: function( url, callback ) {
135 return jQuery.get(url, null, callback, "script");
138 getJSON: function( url, data, callback ) {
139 return jQuery.get(url, data, callback, "json");
142 post: function( url, data, callback, type ) {
143 // shift arguments if data argument was omited
144 if ( jQuery.isFunction( data ) ) {
145 type = type || callback;
159 ajaxSetup: function( settings ) {
160 jQuery.extend( jQuery.ajaxSettings, settings );
167 contentType: "application/x-www-form-urlencoded",
177 // Create the request object; Microsoft failed to properly
178 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
179 // This function can be overriden by calling jQuery.ajaxSetup
181 return window.ActiveXObject ?
182 new ActiveXObject("Microsoft.XMLHTTP") :
183 new XMLHttpRequest();
186 xml: "application/xml, text/xml",
188 script: "text/javascript, application/javascript",
189 json: "application/json, text/javascript",
195 // Last-Modified header cache for next request
199 ajax: function( origSettings ) {
200 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings);
202 var jsonp, status, data,
203 callbackContext = s.context || s,
204 type = s.type.toUpperCase();
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 window[ jsonp ] = window[ jsonp ] || function( tmp ) {
244 window[ jsonp ] = undefined;
247 delete window[ jsonp ];
251 head.removeChild( script );
256 if ( s.dataType === "script" && s.cache === null ) {
260 if ( s.cache === false && type === "GET" ) {
263 // try replacing _= if it is there
264 var ret = s.url.replace(rts, "$1_=" + ts + "$2");
266 // if nothing was replaced, add timestamp to the end
267 s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
270 // If data is available, append data to url for get requests
271 if ( s.data && type === "GET" ) {
272 s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
275 // Watch for a new set of requests
276 if ( s.global && ! jQuery.active++ ) {
277 jQuery.event.trigger( "ajaxStart" );
280 // Matches an absolute URL, and saves the domain
281 var parts = rurl.exec( s.url ),
282 remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
284 // If we're requesting a remote document
285 // and trying to load JSON or Script with a GET
286 if ( s.dataType === "script" && type === "GET" && remote ) {
287 var head = document.getElementsByTagName("head")[0] || document.documentElement;
288 var script = document.createElement("script");
290 if ( s.scriptCharset ) {
291 script.charset = s.scriptCharset;
294 // Handle Script loading
298 // Attach handlers for all browsers
299 script.onload = script.onreadystatechange = function() {
300 if ( !done && (!this.readyState ||
301 this.readyState === "loaded" || this.readyState === "complete") ) {
306 // Handle memory leak in IE
307 script.onload = script.onreadystatechange = null;
308 if ( head && script.parentNode ) {
309 head.removeChild( script );
315 // Use insertBefore instead of appendChild to circumvent an IE6 bug.
316 // This arises when a base node is used (#2709 and #4378).
317 head.insertBefore( script, head.firstChild );
319 // We handle everything using the script element injection
323 var requestDone = false;
325 // Create the request object
329 // Passing null username, generates a login popup on Opera (#2865)
331 xhr.open(type, s.url, s.async, s.username, s.password);
333 xhr.open(type, s.url, s.async);
336 // Need an extra try/catch for cross domain requests in Firefox 3
338 // Set the correct header, if data is being sent
339 if ( s.data || origSettings && origSettings.contentType ) {
340 xhr.setRequestHeader("Content-Type", s.contentType);
343 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
344 if ( s.ifModified ) {
345 if ( jQuery.lastModified[s.url] ) {
346 xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
349 if ( jQuery.etag[s.url] ) {
350 xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
354 // Set header so the called script knows that it's an XMLHttpRequest
355 // Only send the header if it's not a remote XHR
357 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
360 // Set the Accepts header for the server, depending on the dataType
361 xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
362 s.accepts[ s.dataType ] + ", */*" :
363 s.accepts._default );
366 // Allow custom headers/mimetypes and early abort
367 if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) {
368 // Handle the global AJAX counter
369 if ( s.global && ! --jQuery.active ) {
370 jQuery.event.trigger( "ajaxStop" );
373 // close opended socket
379 trigger("ajaxSend", [xhr, s]);
382 // Wait for a response to come back
383 var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
384 // The request was aborted, clear the interval and decrement jQuery.active
385 if ( !xhr || xhr.readyState === 0 ) {
387 xhr.onreadystatechange = jQuery.noop;
389 // Handle the global AJAX counter
390 if ( s.global && ! --jQuery.active ) {
391 jQuery.event.trigger( "ajaxStop" );
394 // The transfer is complete and the data is available, or the request timed out
395 } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
397 xhr.onreadystatechange = jQuery.noop;
399 status = isTimeout === "timeout" ?
401 !jQuery.httpSuccess( xhr ) ?
403 s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
407 if ( status === "success" ) {
408 // Watch for, and catch, XML document parse errors
410 // process the data (runs the xml through httpData regardless of callback)
411 data = jQuery.httpData( xhr, s.dataType, s );
413 status = "parsererror";
417 // Make sure that the request was successful or notmodified
418 if ( status === "success" || status === "notmodified" ) {
419 // JSONP handles its own success callback
424 jQuery.handleError(s, xhr, status);
427 // Fire the complete handlers
430 if ( isTimeout === "timeout" ) {
442 if ( s.async && s.timeout > 0 ) {
443 setTimeout(function() {
444 // Check to see if the request is still happening
445 if ( xhr && !requestDone ) {
446 onreadystatechange( "timeout" );
453 xhr.send( type === "POST" || type === "PUT" ? s.data : null );
455 jQuery.handleError(s, xhr, null, e);
456 // Fire the complete handlers
460 // firefox 1.5 doesn't fire statechange for sync requests
462 onreadystatechange();
466 // If a local callback was specified, fire it and pass it the data
468 s.success.call( callbackContext, data, status, xhr );
471 // Fire the global callback
473 trigger( "ajaxSuccess", [xhr, s] );
477 function complete() {
480 s.complete.call( callbackContext, xhr, status);
483 // The request was completed
485 trigger( "ajaxComplete", [xhr, s] );
488 // Handle the global AJAX counter
489 if ( s.global && ! --jQuery.active ) {
490 jQuery.event.trigger( "ajaxStop" );
494 function trigger(type, args) {
495 (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
498 // return XMLHttpRequest to allow aborting the request etc.
502 handleError: function( s, xhr, status, e ) {
503 // If a local callback was specified, fire it
505 s.error.call( s.context || window, xhr, status, e );
508 // Fire the global callback
510 (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
514 // Counter for holding the number of active queries
517 // Determines if an XMLHttpRequest was successful or not
518 httpSuccess: function( xhr ) {
520 // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
521 return !xhr.status && location.protocol === "file:" ||
522 // Opera returns 0 when status is 304
523 ( xhr.status >= 200 && xhr.status < 300 ) ||
524 xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
530 // Determines if an XMLHttpRequest returns NotModified
531 httpNotModified: function( xhr, url ) {
532 var lastModified = xhr.getResponseHeader("Last-Modified"),
533 etag = xhr.getResponseHeader("Etag");
535 if ( lastModified ) {
536 jQuery.lastModified[url] = lastModified;
540 jQuery.etag[url] = etag;
543 // Opera returns 0 when status is 304
544 return xhr.status === 304 || xhr.status === 0;
547 httpData: function( xhr, type, s ) {
548 var ct = xhr.getResponseHeader("content-type"),
549 xml = type === "xml" || !type && ct && ct.indexOf("xml") >= 0,
550 data = xml ? xhr.responseXML : xhr.responseText;
552 if ( xml && data.documentElement.nodeName === "parsererror" ) {
556 // Allow a pre-filtering function to sanitize the response
557 // s is checked to keep backwards compatibility
558 if ( s && s.dataFilter ) {
559 data = s.dataFilter( data, type );
562 // The filter can actually parse the response
563 if ( typeof data === "string" ) {
565 // If the type is "script", eval it in global context
566 if ( type === "script" ) {
567 jQuery.globalEval( data );
570 // Get the JavaScript object, if JSON is used.
571 if ( type === "json" ) {
572 if ( typeof JSON === "object" && JSON.parse ) {
573 data = JSON.parse( data );
575 data = (new Function("return " + data))();
583 // Serialize an array of form elements or a set of
584 // key/values into a query string
585 param: function( a, traditional ) {
589 // Set traditional to true for jQuery <= 1.3.2 behavior.
590 if ( traditional === undefined ) {
591 traditional = jQuery.ajaxSettings.traditional;
594 function add( key, value ) {
595 // If value is a function, invoke it and return its value
596 value = jQuery.isFunction(value) ? value() : value;
597 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
600 // If an array was passed in, assume that it is an array of form elements.
601 if ( jQuery.isArray(a) || a.jquery ) {
602 // Serialize the form elements
603 jQuery.each( a, function() {
604 add( this.name, this.value );
608 // If traditional, encode the "old" way (the way 1.3.2 or older
609 // did it), otherwise encode params recursively.
610 jQuery.each( a, function buildParams( prefix, obj ) {
612 if ( jQuery.isArray(obj) ) {
613 // Serialize array item.
614 jQuery.each( obj, function( i, v ) {
616 // Treat each array item as a scalar.
619 // If array item is non-scalar (array or object), encode its
620 // numeric index to resolve deserialization ambiguity issues.
621 // Note that rack (as of 1.0.0) can't currently deserialize
622 // nested arrays properly, and attempting to do so may cause
623 // a server error. Possible fixes are to modify rack's
624 // deserialization algorithm or to provide an option or flag
625 // to force array serialization to be shallow.
626 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v );
630 } else if ( !traditional && typeof obj === "object" ) {
631 // Serialize object item.
632 jQuery.each( obj, function( k, v ) {
633 buildParams( prefix + "[" + k + "]", v );
637 // Serialize scalar item.
643 // Return the resulting serialization
644 return s.join("&").replace(r20, "+");