2 load: function( url, params, callback ) {
3 if ( jQuery.isFunction( url ) )
4 return this.bind("load", url);
6 var off = url.indexOf(" ");
8 var selector = url.slice(off, url.length);
9 url = url.slice(0, off);
12 callback = callback || function(){};
14 // Default to a GET request
17 // If the second parameter was provided
20 if ( jQuery.isFunction( params ) ) {
21 // We assume that it's the callback
25 // Otherwise, build a param string
27 params = jQuery.param( params );
33 // Request the remote document
39 complete: function(res, status){
40 // If successful, inject the HTML into all the matched elements
41 if ( status == "success" || status == "notmodified" )
42 // See if a selector was specified
44 // Create a dummy div to hold the results
46 // inject the contents of the document in, removing the scripts
47 // to avoid any 'Permission Denied' errors in IE
48 .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
50 // Locate the specified elements
53 // If not, just inject the full result
56 self.each( callback, [res.responseText, status, res] );
62 serialize: function() {
63 return jQuery.param(this.serializeArray());
65 serializeArray: function() {
66 return this.map(function(){
67 return jQuery.nodeName(this, "form") ?
68 jQuery.makeArray(this.elements) : this;
71 return this.name && !this.disabled &&
72 (this.checked || /select|textarea/i.test(this.nodeName) ||
73 /text|hidden|password/i.test(this.type));
75 .map(function(i, elem){
76 var val = jQuery(this).val();
77 return val == null ? null :
78 val.constructor == Array ?
79 jQuery.map( val, function(val, i){
80 return {name: elem.name, value: val};
82 {name: elem.name, value: val};
87 // Attach a bunch of functions for handling common AJAX events
88 jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
89 jQuery.fn[o] = function(f){
90 return this.bind(o, f);
94 var jsc = (new Date).getTime();
97 get: function( url, data, callback, type ) {
98 // shift arguments if data argument was ommited
99 if ( jQuery.isFunction( data ) ) {
113 getScript: function( url, callback ) {
114 return jQuery.get(url, null, callback, "script");
117 getJSON: function( url, data, callback ) {
118 return jQuery.get(url, data, callback, "json");
121 post: function( url, data, callback, type ) {
122 if ( jQuery.isFunction( data ) ) {
136 ajaxSetup: function( settings ) {
137 jQuery.extend( jQuery.ajaxSettings, settings );
144 contentType: "application/x-www-form-urlencoded",
151 xml: "application/xml, text/xml",
153 script: "text/javascript, application/javascript",
154 json: "application/json, text/javascript",
160 // Last-Modified header cache for next request
163 ajax: function( s ) {
164 var jsonp, jsre = /=\?(&|$)/g, status, data;
166 // Extend the settings, but re-extend 's' so that it can be
167 // checked again later (in the test suite, specifically)
168 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
170 // convert data if not already a string
171 if ( s.data && s.processData && typeof s.data != "string" )
172 s.data = jQuery.param(s.data);
174 // Handle JSONP Parameter Callbacks
175 if ( s.dataType == "jsonp" ) {
176 if ( s.type.toLowerCase() == "get" ) {
177 if ( !s.url.match(jsre) )
178 s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
179 } else if ( !s.data || !s.data.match(jsre) )
180 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
184 // Build temporary JSONP function
185 if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
186 jsonp = "jsonp" + jsc++;
188 // Replace the =? sequence both in the query string and the data
190 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
191 s.url = s.url.replace(jsre, "=" + jsonp + "$1");
193 // We need to make sure
194 // that a JSONP style response is executed properly
195 s.dataType = "script";
197 // Handle JSONP-style loading
198 window[ jsonp ] = function(tmp){
203 window[ jsonp ] = undefined;
204 try{ delete window[ jsonp ]; } catch(e){}
206 head.removeChild( script );
210 if ( s.dataType == "script" && s.cache == null )
213 if ( s.cache === false && s.type.toLowerCase() == "get" ) {
214 var ts = (new Date()).getTime();
215 // try replacing _= if it is there
216 var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
217 // if nothing was replaced, add timestamp to the end
218 s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
221 // If data is available, append data to url for get requests
222 if ( s.data && s.type.toLowerCase() == "get" ) {
223 s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
225 // IE likes to send both get and post data, prevent this
229 // Watch for a new set of requests
230 if ( s.global && ! jQuery.active++ )
231 jQuery.event.trigger( "ajaxStart" );
233 // If we're requesting a remote document
234 // and trying to load JSON or Script with a GET
235 if ( (!s.url.indexOf("http") || !s.url.indexOf("//")) && s.dataType == "script" && s.type.toLowerCase() == "get" ) {
236 var head = document.getElementsByTagName("head")[0];
237 var script = document.createElement("script");
240 script.charset = s.scriptCharset;
242 // Handle Script loading
246 // Attach handlers for all browsers
247 script.onload = script.onreadystatechange = function(){
248 if ( !done && (!this.readyState ||
249 this.readyState == "loaded" || this.readyState == "complete") ) {
253 head.removeChild( script );
258 head.appendChild(script);
260 // We handle everything using the script element injection
264 var requestDone = false;
266 // Create the request object; Microsoft failed to properly
267 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
268 var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
271 xml.open(s.type, s.url, s.async, s.username, s.password);
273 // Need an extra try/catch for cross domain requests in Firefox 3
275 // Set the correct header, if data is being sent
277 xml.setRequestHeader("Content-Type", s.contentType);
279 // Set the If-Modified-Since header, if ifModified mode.
281 xml.setRequestHeader("If-Modified-Since",
282 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
284 // Set header so the called script knows that it's an XMLHttpRequest
285 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
287 // Set the Accepts header for the server, depending on the dataType
288 xml.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
289 s.accepts[ s.dataType ] + ", */*" :
290 s.accepts._default );
293 // Allow custom headers/mimetypes
295 var beforeSendSuccess = s.beforeSend(xml, s);
297 if( beforeSendSuccess === false )
301 jQuery.event.trigger("ajaxSend", [xml, s]);
303 // Wait for a response to come back
304 var onreadystatechange = function(isTimeout){
305 // The transfer is complete and the data is available, or the request timed out
306 if ( !requestDone && xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
309 // clear poll interval
315 status = isTimeout == "timeout" && "timeout" ||
316 !jQuery.httpSuccess( xml ) && "error" ||
317 s.ifModified && jQuery.httpNotModified( xml, s.url ) && "notmodified" ||
320 if ( status == "success" ) {
321 // Watch for, and catch, XML document parse errors
323 // process the data (runs the xml through httpData regardless of callback)
324 data = jQuery.httpData( xml, s.dataType );
326 status = "parsererror";
330 // Make sure that the request was successful or notmodified
331 if ( status == "success" ) {
332 // Cache Last-Modified header, if ifModified mode.
335 modRes = xml.getResponseHeader("Last-Modified");
336 } catch(e) {} // swallow exception thrown by FF if header is not available
338 if ( s.ifModified && modRes )
339 jQuery.lastModified[s.url] = modRes;
341 // JSONP handles its own success callback
345 jQuery.handleError(s, xml, status);
347 // Fire the complete handlers
357 // don't attach the handler to the request, just poll it instead
358 var ival = setInterval(onreadystatechange, 13);
362 setTimeout(function(){
363 // Check to see if the request is still happening
365 // Cancel the request
369 onreadystatechange( "timeout" );
378 jQuery.handleError(s, xml, null, e);
381 // firefox 1.5 doesn't fire statechange for sync requests
383 onreadystatechange();
386 // If a local callback was specified, fire it and pass it the data
388 s.success( data, status );
390 // Fire the global callback
392 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
398 s.complete(xml, status);
400 // The request was completed
402 jQuery.event.trigger( "ajaxComplete", [xml, s] );
404 // Handle the global AJAX counter
405 if ( s.global && ! --jQuery.active )
406 jQuery.event.trigger( "ajaxStop" );
409 // return XMLHttpRequest to allow aborting the request etc.
413 handleError: function( s, xml, status, e ) {
414 // If a local callback was specified, fire it
415 if ( s.error ) s.error( xml, status, e );
417 // Fire the global callback
419 jQuery.event.trigger( "ajaxError", [xml, s, e] );
422 // Counter for holding the number of active queries
425 // Determines if an XMLHttpRequest was successful or not
426 httpSuccess: function( r ) {
428 // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
429 return !r.status && location.protocol == "file:" ||
430 ( r.status >= 200 && r.status < 300 ) || r.status == 304 || r.status == 1223 ||
431 jQuery.browser.safari && r.status == undefined;
436 // Determines if an XMLHttpRequest returns NotModified
437 httpNotModified: function( xml, url ) {
439 var xmlRes = xml.getResponseHeader("Last-Modified");
441 // Firefox always returns 200. check Last-Modified date
442 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
443 jQuery.browser.safari && xml.status == undefined;
448 httpData: function( r, type ) {
449 var ct = r.getResponseHeader("content-type");
450 var xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0;
451 var data = xml ? r.responseXML : r.responseText;
453 if ( xml && data.documentElement.tagName == "parsererror" )
456 // If the type is "script", eval it in global context
457 if ( type == "script" )
458 jQuery.globalEval( data );
460 // Get the JavaScript object, if JSON is used.
461 if ( type == "json" )
462 data = eval("(" + data + ")");
467 // Serialize an array of form elements or a set of
468 // key/values into a query string
469 param: function( a ) {
472 // If an array was passed in, assume that it is an array
474 if ( a.constructor == Array || a.jquery )
475 // Serialize the form elements
476 jQuery.each( a, function(){
477 s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
480 // Otherwise, assume that it's an object of key/value pairs
482 // Serialize the key/values
484 // If the value is an array then the key names need to be repeated
485 if ( a[j] && a[j].constructor == Array )
486 jQuery.each( a[j], function(){
487 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
490 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
492 // Return the resulting serialization
493 return s.join("&").replace(/%20/g, "+");