2 rscript = /<script(.|\s)*?\/script>/g,
3 rselectTextarea = /select|textarea/i,
4 rinput = /text|hidden|password|search/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 );
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",
176 // Create the request object; Microsoft failed to properly
177 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
178 // This function can be overriden by calling jQuery.ajaxSetup
180 return window.ActiveXObject ?
181 new ActiveXObject("Microsoft.XMLHTTP") :
182 new XMLHttpRequest();
185 xml: "application/xml, text/xml",
187 script: "text/javascript, application/javascript",
188 json: "application/json, text/javascript",
194 // Last-Modified header cache for next request
198 ajax: function( s ) {
199 // Extend the settings, but re-extend 's' so that it can be
200 // checked again later (in the test suite, specifically)
201 s = jQuery.extend(true, {}, jQuery.ajaxSettings, s);
203 var jsonp, status, data,
204 callbackContext = s.context || window,
205 type = s.type.toUpperCase();
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);
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 = "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 ] = function(tmp){
245 window[ jsonp ] = undefined;
246 try{ delete window[ jsonp ]; } catch(e){}
248 head.removeChild( script );
253 if ( s.dataType === "script" && s.cache === null ) {
257 if ( s.cache === false && type === "GET" ) {
260 // try replacing _= if it is there
261 var ret = s.url.replace(rts, "$1_=" + ts + "$2");
263 // if nothing was replaced, add timestamp to the end
264 s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
267 // If data is available, append data to url for get requests
268 if ( s.data && type === "GET" ) {
269 s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
272 // Watch for a new set of requests
273 if ( s.global && ! jQuery.active++ ) {
274 jQuery.event.trigger( "ajaxStart" );
277 // Matches an absolute URL, and saves the domain
278 var parts = rurl.exec( s.url );
280 // If we're requesting a remote document
281 // and trying to load JSON or Script with a GET
282 if ( s.dataType === "script" && type === "GET" && parts
283 && ( parts[1] && parts[1] !== location.protocol || parts[2] !== location.host )) {
285 var head = document.getElementsByTagName("head")[0] || document.documentElement;
286 var script = document.createElement("script");
288 if ( s.scriptCharset ) {
289 script.charset = s.scriptCharset;
292 // Handle Script loading
296 // Attach handlers for all browsers
297 script.onload = script.onreadystatechange = function(){
298 if ( !done && (!this.readyState ||
299 this.readyState === "loaded" || this.readyState === "complete") ) {
304 // Handle memory leak in IE
305 script.onload = script.onreadystatechange = null;
306 if ( head && script.parentNode ) {
307 head.removeChild( script );
313 // Use insertBefore instead of appendChild to circumvent an IE6 bug.
314 // This arises when a base node is used (#2709 and #4378).
315 head.insertBefore( script, head.firstChild );
317 // We handle everything using the script element injection
321 var requestDone = false;
323 // Create the request object
327 // Passing null username, generates a login popup on Opera (#2865)
329 xhr.open(type, s.url, s.async, s.username, s.password);
331 xhr.open(type, s.url, s.async);
334 // Need an extra try/catch for cross domain requests in Firefox 3
336 // Set the correct header, if data is being sent
338 xhr.setRequestHeader("Content-Type", s.contentType);
341 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
342 if ( s.ifModified ) {
343 if ( jQuery.lastModified[s.url] ) {
344 xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
347 if ( jQuery.etag[s.url] ) {
348 xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
352 // Set header so the called script knows that it's an XMLHttpRequest
353 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
355 // Set the Accepts header for the server, depending on the dataType
356 xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
357 s.accepts[ s.dataType ] + ", */*" :
358 s.accepts._default );
361 // Allow custom headers/mimetypes and early abort
362 if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) {
363 // Handle the global AJAX counter
364 if ( s.global && ! --jQuery.active ) {
365 jQuery.event.trigger( "ajaxStop" );
368 // close opended socket
374 trigger("ajaxSend", [xhr, s]);
377 // Wait for a response to come back
378 var onreadystatechange = function(isTimeout){
379 // The request was aborted, clear the interval and decrement jQuery.active
380 if ( !xhr || xhr.readyState === 0 ) {
382 // clear poll interval
383 clearInterval( ival );
386 // Handle the global AJAX counter
387 if ( s.global && ! --jQuery.active ) {
388 jQuery.event.trigger( "ajaxStop" );
392 // The transfer is complete and the data is available, or the request timed out
393 } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
396 // clear poll interval
402 status = isTimeout === "timeout" ?
404 !jQuery.httpSuccess( xhr ) ?
406 s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
410 if ( status === "success" ) {
411 // Watch for, and catch, XML document parse errors
413 // process the data (runs the xml through httpData regardless of callback)
414 data = jQuery.httpData( xhr, s.dataType, s );
416 status = "parsererror";
420 // Make sure that the request was successful or notmodified
421 if ( status === "success" || status === "notmodified" ) {
422 // JSONP handles its own success callback
427 jQuery.handleError(s, xhr, status);
430 // Fire the complete handlers
445 // don't attach the handler to the request, just poll it instead
446 var ival = setInterval(onreadystatechange, 13);
449 if ( s.timeout > 0 ) {
450 setTimeout(function(){
451 // Check to see if the request is still happening
452 if ( xhr && !requestDone ) {
453 onreadystatechange( "timeout" );
461 xhr.send( type === "POST" || type === "PUT" ? s.data : null );
463 jQuery.handleError(s, xhr, null, e);
464 // Fire the complete handlers
468 // firefox 1.5 doesn't fire statechange for sync requests
470 onreadystatechange();
474 // If a local callback was specified, fire it and pass it the data
476 s.success.call( callbackContext, data, status, xhr );
479 // Fire the global callback
481 trigger( "ajaxSuccess", [xhr, s] );
488 s.complete.call( callbackContext, xhr, status);
491 // The request was completed
493 trigger( "ajaxComplete", [xhr, s] );
496 // Handle the global AJAX counter
497 if ( s.global && ! --jQuery.active ) {
498 jQuery.event.trigger( "ajaxStop" );
502 function trigger(type, args){
503 (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
506 // return XMLHttpRequest to allow aborting the request etc.
510 handleError: function( s, xhr, status, e ) {
511 // If a local callback was specified, fire it
513 s.error.call( s.context || window, xhr, status, e );
516 // Fire the global callback
518 (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
522 // Counter for holding the number of active queries
525 // Determines if an XMLHttpRequest was successful or not
526 httpSuccess: function( xhr ) {
528 // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
529 return !xhr.status && location.protocol === "file:" ||
530 // Opera returns 0 when status is 304
531 ( xhr.status >= 200 && xhr.status < 300 ) ||
532 xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
538 // Determines if an XMLHttpRequest returns NotModified
539 httpNotModified: function( xhr, url ) {
540 var lastModified = xhr.getResponseHeader("Last-Modified"),
541 etag = xhr.getResponseHeader("Etag");
543 if ( lastModified ) {
544 jQuery.lastModified[url] = lastModified;
548 jQuery.etag[url] = etag;
551 // Opera returns 0 when status is 304
552 return xhr.status === 304 || xhr.status === 0;
555 httpData: function( xhr, type, s ) {
556 var ct = xhr.getResponseHeader("content-type"),
557 xml = type === "xml" || !type && ct && ct.indexOf("xml") >= 0,
558 data = xml ? xhr.responseXML : xhr.responseText;
560 if ( xml && data.documentElement.nodeName === "parsererror" ) {
564 // Allow a pre-filtering function to sanitize the response
565 // s is checked to keep backwards compatibility
566 if ( s && s.dataFilter ) {
567 data = s.dataFilter( data, type );
570 // The filter can actually parse the response
571 if ( typeof data === "string" ) {
573 // If the type is "script", eval it in global context
574 if ( type === "script" ) {
575 jQuery.globalEval( data );
578 // Get the JavaScript object, if JSON is used.
579 if ( type === "json" ) {
580 if ( typeof JSON === "object" && JSON.parse ) {
581 data = JSON.parse( data );
583 data = (new Function("return " + data))();
591 // Serialize an array of form elements or a set of
592 // key/values into a query string
593 param: function( a ) {
595 param_traditional = jQuery.param.traditional;
597 function add( key, value ){
598 // If value is a function, invoke it and return its value
599 value = jQuery.isFunction(value) ? value() : value;
600 s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
603 // If an array was passed in, assume that it is an array
605 if ( jQuery.isArray(a) || a.jquery )
606 // Serialize the form elements
607 jQuery.each( a, function() {
608 add( this.name, this.value );
612 // Encode parameters from object, recursively. If
613 // jQuery.param.traditional is set, encode the "old" way
614 // (the way 1.3.2 or older did it)
615 jQuery.each( a, function buildParams( prefix, obj ) {
617 if ( jQuery.isArray(obj) )
618 jQuery.each( obj, function(i,v){
619 // Due to rails' limited request param syntax, numeric array
620 // indices are not supported. To avoid serialization ambiguity
621 // issues, serialized arrays can only contain scalar values. php
622 // does not have this issue, but we should go with the lowest
623 // common denominator
624 add( prefix + ( param_traditional ? "" : "[]" ), v );
627 else if ( typeof obj == "object" )
628 if ( param_traditional )
632 jQuery.each( obj, function(k,v){
633 buildParams( prefix ? prefix + "[" + k + "]" : k, v );
641 // Return the resulting serialization
642 return s.join("&").replace(r20, "+");