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 );
20 var off = url.indexOf(" ");
22 var selector = url.slice(off, url.length);
23 url = url.slice(0, off);
26 // Default to a GET request
29 // If the second parameter was provided
32 if ( jQuery.isFunction( params ) ) {
33 // We assume that it's the callback
37 // Otherwise, build a param string
38 } else if ( typeof params === "object" ) {
39 params = jQuery.param( params );
44 // Request the remote document
51 complete: function(res, status){
52 // If successful, inject the HTML into all the matched elements
53 if ( status === "success" || status === "notmodified" ) {
54 // See if a selector was specified
56 // Create a dummy div to hold the results
58 // inject the contents of the document in, removing the scripts
59 // to avoid any 'Permission Denied' errors in IE
60 .append(res.responseText.replace(rscript, ""))
62 // Locate the specified elements
65 // If not, just inject the full result
70 this.each( callback, [res.responseText, status, res] );
78 serialize: function() {
79 return jQuery.param(this.serializeArray());
81 serializeArray: function() {
82 return this.map(function(){
83 return this.elements ? jQuery.makeArray(this.elements) : this;
86 return this.name && !this.disabled &&
87 (this.checked || rselectTextarea.test(this.nodeName) ||
88 rinput.test(this.type));
90 .map(function(i, elem){
91 var val = jQuery(this).val();
96 jQuery.map( val, function(val, i){
97 return {name: elem.name, value: val};
99 {name: elem.name, value: val};
104 // Attach a bunch of functions for handling common AJAX events
105 jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
106 jQuery.fn[o] = function(f){
107 return this.bind(o, f);
113 get: function( url, data, callback, type ) {
114 // shift arguments if data argument was ommited
115 if ( jQuery.isFunction( data ) ) {
129 getScript: function( url, callback ) {
130 return jQuery.get(url, null, callback, "script");
133 getJSON: function( url, data, callback ) {
134 return jQuery.get(url, data, callback, "json");
137 post: function( url, data, callback, type ) {
138 if ( jQuery.isFunction( data ) ) {
152 ajaxSetup: function( settings ) {
153 jQuery.extend( jQuery.ajaxSettings, settings );
160 contentType: "application/x-www-form-urlencoded",
169 // Create the request object; Microsoft failed to properly
170 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
171 // This function can be overriden by calling jQuery.ajaxSetup
173 return window.ActiveXObject ?
174 new ActiveXObject("Microsoft.XMLHTTP") :
175 new XMLHttpRequest();
178 xml: "application/xml, text/xml",
180 script: "text/javascript, application/javascript",
181 json: "application/json, text/javascript",
187 // Last-Modified header cache for next request
191 ajax: function( s ) {
192 // Extend the settings, but re-extend 's' so that it can be
193 // checked again later (in the test suite, specifically)
194 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
196 var jsonp, status, data,
197 callbackContext = s.context || window,
198 type = s.type.toUpperCase();
200 // convert data if not already a string
201 if ( s.data && s.processData && typeof s.data !== "string" ) {
202 s.data = jQuery.param(s.data);
205 // Handle JSONP Parameter Callbacks
206 if ( s.dataType === "jsonp" ) {
207 if ( type === "GET" ) {
208 if ( !jsre.test( s.url ) ) {
209 s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
211 } else if ( !s.data || !jsre.test(s.data) ) {
212 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
217 // Build temporary JSONP function
218 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
219 jsonp = "jsonp" + jsc++;
221 // Replace the =? sequence both in the query string and the data
223 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
226 s.url = s.url.replace(jsre, "=" + jsonp + "$1");
228 // We need to make sure
229 // that a JSONP style response is executed properly
230 s.dataType = "script";
232 // Handle JSONP-style loading
233 window[ jsonp ] = function(tmp){
238 window[ jsonp ] = undefined;
239 try{ delete window[ jsonp ]; } catch(e){}
241 head.removeChild( script );
246 if ( s.dataType === "script" && s.cache === null ) {
250 if ( s.cache === false && type === "GET" ) {
253 // try replacing _= if it is there
254 var ret = s.url.replace(rts, "$1_=" + ts + "$2");
256 // if nothing was replaced, add timestamp to the end
257 s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
260 // If data is available, append data to url for get requests
261 if ( s.data && type === "GET" ) {
262 s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
265 // Watch for a new set of requests
266 if ( s.global && ! jQuery.active++ ) {
267 jQuery.event.trigger( "ajaxStart" );
270 // Matches an absolute URL, and saves the domain
271 var parts = rurl.exec( s.url );
273 // If we're requesting a remote document
274 // and trying to load JSON or Script with a GET
275 if ( s.dataType === "script" && type === "GET" && parts
276 && ( parts[1] && parts[1] !== location.protocol || parts[2] !== location.host )) {
278 var head = document.getElementsByTagName("head")[0] || document.documentElement;
279 var script = document.createElement("script");
281 if ( s.scriptCharset ) {
282 script.charset = s.scriptCharset;
285 // Handle Script loading
289 // Attach handlers for all browsers
290 script.onload = script.onreadystatechange = function(){
291 if ( !done && (!this.readyState ||
292 this.readyState === "loaded" || this.readyState === "complete") ) {
297 // Handle memory leak in IE
298 script.onload = script.onreadystatechange = null;
299 if ( head && script.parentNode ) {
300 head.removeChild( script );
306 // Use insertBefore instead of appendChild to circumvent an IE6 bug.
307 // This arises when a base node is used (#2709 and #4378).
308 head.insertBefore( script, head.firstChild );
310 // We handle everything using the script element injection
314 var requestDone = false;
316 // Create the request object
320 // Passing null username, generates a login popup on Opera (#2865)
322 xhr.open(type, s.url, s.async, s.username, s.password);
324 xhr.open(type, s.url, s.async);
327 // Need an extra try/catch for cross domain requests in Firefox 3
329 // Set the correct header, if data is being sent
331 xhr.setRequestHeader("Content-Type", s.contentType);
334 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
335 if ( s.ifModified ) {
336 if ( jQuery.lastModified[s.url] ) {
337 xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
340 if ( jQuery.etag[s.url] ) {
341 xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
345 // Set header so the called script knows that it's an XMLHttpRequest
346 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
348 // Set the Accepts header for the server, depending on the dataType
349 xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
350 s.accepts[ s.dataType ] + ", */*" :
351 s.accepts._default );
354 // Allow custom headers/mimetypes and early abort
355 if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) {
356 // Handle the global AJAX counter
357 if ( s.global && ! --jQuery.active ) {
358 jQuery.event.trigger( "ajaxStop" );
361 // close opended socket
367 trigger("ajaxSend", [xhr, s]);
370 // Wait for a response to come back
371 var onreadystatechange = function(isTimeout){
372 // The request was aborted, clear the interval and decrement jQuery.active
373 if ( !xhr || xhr.readyState === 0 ) {
375 // clear poll interval
376 clearInterval( ival );
379 // Handle the global AJAX counter
380 if ( s.global && ! --jQuery.active ) {
381 jQuery.event.trigger( "ajaxStop" );
385 // The transfer is complete and the data is available, or the request timed out
386 } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
389 // clear poll interval
395 status = isTimeout === "timeout" ?
397 !jQuery.httpSuccess( xhr ) ?
399 s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
403 if ( status === "success" ) {
404 // Watch for, and catch, XML document parse errors
406 // process the data (runs the xml through httpData regardless of callback)
407 data = jQuery.httpData( xhr, s.dataType, s );
409 status = "parsererror";
413 // Make sure that the request was successful or notmodified
414 if ( status === "success" || status === "notmodified" ) {
415 // JSONP handles its own success callback
420 jQuery.handleError(s, xhr, status);
423 // Fire the complete handlers
438 // don't attach the handler to the request, just poll it instead
439 var ival = setInterval(onreadystatechange, 13);
442 if ( s.timeout > 0 ) {
443 setTimeout(function(){
444 // Check to see if the request is still happening
445 if ( xhr && !requestDone ) {
446 onreadystatechange( "timeout" );
454 xhr.send( type === "POST" || type === "PUT" ? s.data : null );
456 jQuery.handleError(s, xhr, null, e);
459 // firefox 1.5 doesn't fire statechange for sync requests
461 onreadystatechange();
465 // If a local callback was specified, fire it and pass it the data
467 s.success.call( callbackContext, data, status );
470 // Fire the global callback
472 trigger( "ajaxSuccess", [xhr, s] );
479 s.complete.call( callbackContext, xhr, status);
482 // The request was completed
484 trigger( "ajaxComplete", [xhr, s] );
487 // Handle the global AJAX counter
488 if ( s.global && ! --jQuery.active ) {
489 jQuery.event.trigger( "ajaxStop" );
493 function trigger(type, args){
494 (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
497 // return XMLHttpRequest to allow aborting the request etc.
501 handleError: function( s, xhr, status, e ) {
502 // If a local callback was specified, fire it
504 s.error.call( s.context || window, xhr, status, e );
507 // Fire the global callback
509 (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
513 // Counter for holding the number of active queries
516 // Determines if an XMLHttpRequest was successful or not
517 httpSuccess: function( xhr ) {
519 // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
520 return !xhr.status && location.protocol === "file:" ||
521 // Opera returns 0 when status is 304
522 ( xhr.status >= 200 && xhr.status < 300 ) ||
523 xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
529 // Determines if an XMLHttpRequest returns NotModified
530 httpNotModified: function( xhr, url ) {
531 var lastModified = xhr.getResponseHeader("Last-Modified"),
532 etag = xhr.getResponseHeader("Etag");
534 if ( lastModified ) {
535 jQuery.lastModified[url] = lastModified;
539 jQuery.etag[url] = etag;
542 // Opera returns 0 when status is 304
543 return xhr.status === 304 || xhr.status === 0;
546 httpData: function( xhr, type, s ) {
547 var ct = xhr.getResponseHeader("content-type"),
548 xml = type === "xml" || !type && ct && ct.indexOf("xml") >= 0,
549 data = xml ? xhr.responseXML : xhr.responseText;
551 if ( xml && data.documentElement.nodeName === "parsererror" ) {
555 // Allow a pre-filtering function to sanitize the response
556 // s is checked to keep backwards compatibility
557 if ( s && s.dataFilter ) {
558 data = s.dataFilter( data, type );
561 // The filter can actually parse the response
562 if ( typeof data === "string" ) {
564 // If the type is "script", eval it in global context
565 if ( type === "script" ) {
566 jQuery.globalEval( data );
569 // Get the JavaScript object, if JSON is used.
570 if ( type === "json" ) {
571 if ( typeof JSON === "object" && JSON.parse ) {
572 data = JSON.parse( data );
574 data = (new Function("return " + data))();
582 // Serialize an array of form elements or a set of
583 // key/values into a query string
584 param: function( a ) {
587 function add( key, value ){
588 s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
591 // If an array was passed in, assume that it is an array
593 if ( jQuery.isArray(a) || a.jquery ) {
594 // Serialize the form elements
595 jQuery.each( a, function() {
596 add( this.name, this.value );
599 // Recursively encode parameters from object,
600 // building a prefix path as we go down
601 function buildParams(obj, prefix)
603 if ( jQuery.isArray(obj) ) {
604 for ( var i = 0, length = obj.length; i < length; i++ ) {
605 buildParams( obj[i], prefix );
607 } else if( typeof(obj) == "object" ) {
608 for ( var j in obj ) {
609 var postfix = ((j.indexOf("[]") > 0) ? "[]" : ""); // move any brackets to the end
610 buildParams(obj[j], (prefix ? (prefix+"["+j.replace("[]", "")+"]"+postfix) : j) );
613 add( prefix, jQuery.isFunction(obj) ? obj() : obj );
619 // Return the resulting serialization
620 return s.join("&").replace(r20, "+");