Rewrote the data conversion logic in ajax. Should be cleaner and faster.
[jquery.git] / src / ajax.js
1 (function( jQuery ) {
2         
3 var rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
4         rselectTextarea = /^(?:select|textarea)/i,
5         rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
6         rbracket = /\[\]$/,
7         rquery = /\?/,
8         r20 = /%20/g,
9
10         // Keep a copy of the old load method
11         _load = jQuery.fn.load;
12
13 jQuery.fn.extend({
14         load: function( url, params, callback ) {
15                 if ( typeof url !== "string" && _load ) {
16                         return _load.apply( this, arguments );
17
18                 // Don't do a request if no elements are being requested
19                 } else if ( !this.length ) {
20                         return this;
21                 }
22
23                 var off = url.indexOf(" ");
24                 if ( off >= 0 ) {
25                         var selector = url.slice(off, url.length);
26                         url = url.slice(0, off);
27                 }
28
29                 // Default to a GET request
30                 var type = "GET";
31
32                 // If the second parameter was provided
33                 if ( params ) {
34                         // If it's a function
35                         if ( jQuery.isFunction( params ) ) {
36                                 // We assume that it's the callback
37                                 callback = params;
38                                 params = null;
39
40                         // Otherwise, build a param string
41                         } else if ( typeof params === "object" ) {
42                                 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
43                                 type = "POST";
44                         }
45                 }
46                 
47                 var self = this;
48                 
49                 // Request the remote document
50                 jQuery.ajax({
51                         url: url,
52                         type: type,
53                         dataType: "html",
54                         data: params,
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
59                                         self.html( selector ?
60                                                 // Create a dummy div to hold the results
61                                                 jQuery("<div>")
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, ""))
65
66                                                         // Locate the specified elements
67                                                         .find(selector) :
68
69                                                 // If not, just inject the full result
70                                                 res.responseText );
71                                 }
72
73                                 if ( callback ) {
74                                         self.each( callback, [res.responseText, status, res] );
75                                 }
76                         }
77                 });
78
79                 return this;
80         },
81
82         serialize: function() {
83                 return jQuery.param(this.serializeArray());
84         },
85
86         serializeArray: function() {
87                 return this.map(function(){
88                         return this.elements ? jQuery.makeArray(this.elements) : this;
89                 })
90                 .filter(function(){
91                         return this.name && !this.disabled &&
92                                 (this.checked || rselectTextarea.test(this.nodeName) ||
93                                         rinput.test(this.type));
94                 })
95                 .map(function(i, elem){
96                         var val = jQuery(this).val();
97
98                         return val == null ?
99                                 null :
100                                 jQuery.isArray(val) ?
101                                         jQuery.map( val, function(val, i){
102                                                 return {name: elem.name, value: val};
103                                         }) :
104                                         {name: elem.name, value: val};
105                 }).get();
106         }
107 });
108
109 // Attach a bunch of functions for handling common AJAX events
110 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(i,o){
111         jQuery.fn[o] = function(f){
112                 return this.bind(o, f);
113         };
114 });
115
116 jQuery.extend({
117
118         get: function( url, data, callback, type ) {
119                 // shift arguments if data argument was omited
120                 if ( jQuery.isFunction( data ) ) {
121                         type = type || callback;
122                         callback = data;
123                         data = null;
124                 }
125
126                 return jQuery.ajax({
127                         type: "GET",
128                         url: url,
129                         data: data,
130                         success: callback,
131                         dataType: type
132                 });
133         },
134
135         getScript: function( url, callback ) {
136                 return jQuery.get(url, null, callback, "script");
137         },
138
139         getJSON: function( url, data, callback ) {
140                 return jQuery.get(url, data, callback, "json");
141         },
142
143         post: function( url, data, callback, type ) {
144                 // shift arguments if data argument was omited
145                 if ( jQuery.isFunction( data ) ) {
146                         type = type || callback;
147                         callback = data;
148                         data = {};
149                 }
150
151                 return jQuery.ajax({
152                         type: "POST",
153                         url: url,
154                         data: data,
155                         success: callback,
156                         dataType: type
157                 });
158         },
159
160         ajaxSetup: function( settings ) {
161                 jQuery.extend( jQuery.ajaxSettings, settings );
162         },
163
164         ajaxSettings: {
165                 url: location.href,
166                 global: true,
167                 type: "GET",
168                 contentType: "application/x-www-form-urlencoded",
169                 processData: true,
170                 async: true,
171                 /*
172                 timeout: 0,
173                 data: null,
174                 dataType: null,
175                 dataTypes: null,
176                 username: null,
177                 password: null,
178                 cache: null,
179                 traditional: false,
180                 */
181                 xhr: function() {
182                         return new window.XMLHttpRequest();
183                 },
184
185                 accepts: {
186                         xml: "application/xml, text/xml",
187                         html: "text/html",
188                         text: "text/plain",
189                         json: "application/json, text/javascript",
190                         "*": "*/*"
191                 },
192
193                 autoDataType: {
194                         xml: /xml/,
195                         html: /html/,
196                         json: /json/
197                 },
198
199                 // Prefilters
200                 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
201                 // 2) These are called:
202                 //    * BEFORE asking for a transport
203                 //    * AFTER param serialization (s.data is a string if s.processData is true)
204                 // 3) key is the dataType
205                 // 4) the catchall symbol "*" can be used
206                 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
207                 prefilters: {},
208
209                 // Transports bindings
210                 // 1) key is the dataType
211                 // 2) the catchall symbol "*" can be used
212                 // 3) selection will start with transport dataType and THEN go to "*" if needed
213                 transports: {},
214
215                 // Checkers
216                 // 1) key is dataType
217                 // 2) they are called to control successful response
218                 // 3) error throws is used as error data
219                 dataCheckers: {
220
221                         // Check if data is a string
222                         "text": function(data) {
223                                 if ( typeof data != "string" ) {
224                                         jQuery.error("typeerror");
225                                 }
226                         },
227
228                         // Check if xml has been properly parsed
229                         "xml": function(data) {
230                                 var documentElement = data ? data.documentElement : data;
231                                 if ( ! documentElement || ! documentElement.nodeName ) {
232                                         jQuery.error("typeerror");
233                                 }
234                                 if ( documentElement.nodeName == "parsererror" ) {
235                                         jQuery.error("parsererror");
236                                 }
237                         }
238                 },
239
240                 // List of data converters
241                 // 1) key format is "source_type => destination_type" (spaces required)
242                 // 2) the catchall symbol "*" can be used for source_type
243                 dataConverters: {
244
245                         // Convert anything to text
246                         "* => text": function(data) {
247                                 return "" + data;
248                         },
249
250                         // Text to html (no transformation)
251                         "text => html": function(data) {
252                                 return data;
253                         },
254
255                         // Evaluate text as a json expression
256                         "text => json": jQuery.parseJSON,
257
258                         // Parse text as xml
259                         "text => xml": function(data) {
260                                 var xml, parser;
261                                 if ( window.DOMParser ) { // Standard
262                                         parser = new DOMParser();
263                                         xml = parser.parseFromString(data,"text/xml");
264                                 } else { // IE
265                                         xml = new ActiveXObject("Microsoft.XMLDOM");
266                                         xml.async="false";
267                                         xml.loadXML(data);
268                                 }
269                                 return xml;
270                         }
271                 }
272         },
273
274         // Main method
275         ajax: function( url , s ) {
276                 
277                 if ( arguments.length === 1 ) {
278                         s = url;
279                         url = s ? s.url : undefined;
280                 }
281                 
282                 return jQuery.xhr().open( s ? s.type : undefined , url ).send( undefined , s );
283                 
284         },
285
286         // Serialize an array of form elements or a set of
287         // key/values into a query string
288         param: function( a, traditional ) {
289                 var s = [],
290                         add = function( key, value ) {
291                                 // If value is a function, invoke it and return its value
292                                 value = jQuery.isFunction(value) ? value() : value;
293                                 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
294                         };
295                 
296                 // Set traditional to true for jQuery <= 1.3.2 behavior.
297                 if ( traditional === undefined ) {
298                         traditional = jQuery.ajaxSettings.traditional;
299                 }
300                 
301                 // If an array was passed in, assume that it is an array of form elements.
302                 if ( jQuery.isArray(a) || a.jquery ) {
303                         // Serialize the form elements
304                         jQuery.each( a, function() {
305                                 add( this.name, this.value );
306                         });
307                         
308                 } else {
309                         // If traditional, encode the "old" way (the way 1.3.2 or older
310                         // did it), otherwise encode params recursively.
311                         for ( var prefix in a ) {
312                                 buildParams( prefix, a[prefix], traditional, add );
313                         }
314                 }
315
316                 // Return the resulting serialization
317                 return s.join("&").replace(r20, "+");
318         }
319 });
320
321 function buildParams( prefix, obj, traditional, add ) {
322         if ( jQuery.isArray(obj) && obj.length ) {
323                 // Serialize array item.
324                 jQuery.each( obj, function( i, v ) {
325                         if ( traditional || rbracket.test( prefix ) ) {
326                                 // Treat each array item as a scalar.
327                                 add( prefix, v );
328
329                         } else {
330                                 // If array item is non-scalar (array or object), encode its
331                                 // numeric index to resolve deserialization ambiguity issues.
332                                 // Note that rack (as of 1.0.0) can't currently deserialize
333                                 // nested arrays properly, and attempting to do so may cause
334                                 // a server error. Possible fixes are to modify rack's
335                                 // deserialization algorithm or to provide an option or flag
336                                 // to force array serialization to be shallow.
337                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
338                         }
339                 });
340                         
341         } else if ( !traditional && obj != null && typeof obj === "object" ) {
342                 // If we see an array here, it is empty and should be treated as an empty
343                 // object
344                 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
345                         add( prefix, "" );
346
347                 // Serialize object item.
348                 } else {
349                         jQuery.each( obj, function( k, v ) {
350                                 buildParams( prefix + "[" + k + "]", v, traditional, add );
351                         });
352                 }
353                                         
354         } else {
355                 // Serialize scalar item.
356                 add( prefix, obj );
357         }
358 }
359
360 // This is still on the jQuery object... for now
361 // Want to move this to jQuery.ajax some day
362 jQuery.extend({
363
364         // Counter for holding the number of active queries
365         active: 0,
366
367         // Last-Modified header cache for next request
368         lastModified: {},
369         etag: {}
370
371 });
372
373 /*
374  * Create the request object; Microsoft failed to properly
375  * implement the XMLHttpRequest in IE7 (can't request local files),
376  * so we use the ActiveXObject when it is available
377  * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
378  * we need a fallback.
379  */
380 if ( window.ActiveXObject ) {
381         jQuery.ajaxSettings.xhr = function() {
382         if ( window.location.protocol !== "file:" ) {
383                 try {
384                         return new window.XMLHttpRequest();
385                 } catch( xhrError ) {}
386         }
387         
388         try {
389                 return new window.ActiveXObject("Microsoft.XMLHTTP");
390         } catch( activeError ) {}
391         };
392 }
393
394 var testXHR = jQuery.ajaxSettings.xhr();
395
396 // Does this browser support XHR requests?
397 jQuery.support.ajax = !!testXHR;
398
399 // Does this browser support crossDomain XHR requests
400 jQuery.support.cors = testXHR && "withCredentials" in testXHR;
401
402 })( jQuery );