Renamed jQuery.xhr.bindTransport as jQuery.xhr.transport. Generalized the implementat...
[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.each( [ "get", "post" ], function( i, method ) {
117         jQuery[ method ] = function( url, data, callback, type ) {
118                 // shift arguments if data argument was omited
119                 if ( jQuery.isFunction( data ) ) {
120                         type = type || callback;
121                         callback = data;
122                         data = null;
123                 }
124
125                 return jQuery.ajax({
126                         type: method,
127                         url: url,
128                         data: data,
129                         success: callback,
130                         dataType: type
131                 });
132         };
133 });
134
135 jQuery.extend({
136
137         getScript: function( url, callback ) {
138                 return jQuery.get(url, null, callback, "script");
139         },
140
141         getJSON: function( url, data, callback ) {
142                 return jQuery.get(url, data, callback, "json");
143         },
144
145         ajaxSetup: function( settings ) {
146                 jQuery.extend( jQuery.ajaxSettings, settings );
147         },
148
149         ajaxSettings: {
150                 url: location.href,
151                 global: true,
152                 type: "GET",
153                 contentType: "application/x-www-form-urlencoded",
154                 processData: true,
155                 async: true,
156                 /*
157                 timeout: 0,
158                 data: null,
159                 dataType: null,
160                 dataTypes: null,
161                 username: null,
162                 password: null,
163                 cache: null,
164                 traditional: false,
165                 */
166                 xhr: function() {
167                         return new window.XMLHttpRequest();
168                 },
169                 xhrResponseFields: {
170                         xml: "XML",
171                         text: "Text",
172                         json: "JSON"
173                 },
174
175                 accepts: {
176                         xml: "application/xml, text/xml",
177                         html: "text/html",
178                         text: "text/plain",
179                         json: "application/json, text/javascript",
180                         "*": "*/*"
181                 },
182
183                 autoDataType: {
184                         xml: /xml/,
185                         html: /html/,
186                         json: /json/
187                 },
188
189                 // Prefilters
190                 // 1) They are useful to introduce custom dataTypes (see transport/jsonp for an example)
191                 // 2) These are called:
192                 //    * BEFORE asking for a transport
193                 //    * AFTER param serialization (s.data is a string if s.processData is true)
194                 // 3) key is the dataType
195                 // 4) the catchall symbol "*" can be used
196                 // 5) execution will start with transport dataType and THEN continue down to "*" if needed
197                 prefilters: {},
198                 
199                 // Transports bindings
200                 // 1) key is the dataType
201                 // 2) the catchall symbol "*" can be used
202                 // 3) selection will start with transport dataType and THEN go to "*" if needed
203                 transports: {},
204                 
205                 // Checkers
206                 // 1) key is dataType
207                 // 2) they are called to control successful response
208                 // 3) error throws is used as error data
209                 dataCheckers: {
210
211                         // Check if data is a string
212                         "text": function(data) {
213                                 if ( typeof data != "string" ) {
214                                         jQuery.error("typeerror");
215                                 }
216                         },
217
218                         // Check if xml has been properly parsed
219                         "xml": function(data) {
220                                 var documentElement = data ? data.documentElement : data;
221                                 if ( ! documentElement || ! documentElement.nodeName ) {
222                                         jQuery.error("typeerror");
223                                 }
224                                 if ( documentElement.nodeName == "parsererror" ) {
225                                         jQuery.error("parsererror");
226                                 }
227                         }
228                 },
229
230                 // List of data converters
231                 // 1) key format is "source_type => destination_type" (spaces required)
232                 // 2) the catchall symbol "*" can be used for source_type
233                 dataConverters: {
234
235                         // Convert anything to text
236                         "* => text": function(data) {
237                                 return "" + data;
238                         },
239
240                         // Text to html (no transformation)
241                         "text => html": function(data) {
242                                 return data;
243                         },
244
245                         // Evaluate text as a json expression
246                         "text => json": jQuery.parseJSON,
247
248                         // Parse text as xml
249                         "text => xml": function(data) {
250                                 var xml, parser;
251                                 if ( window.DOMParser ) { // Standard
252                                         parser = new DOMParser();
253                                         xml = parser.parseFromString(data,"text/xml");
254                                 } else { // IE
255                                         xml = new ActiveXObject("Microsoft.XMLDOM");
256                                         xml.async="false";
257                                         xml.loadXML(data);
258                                 }
259                                 return xml;
260                         }
261                 }
262         },
263
264         // Main method
265         ajax: function( url , s ) {
266
267                 if ( arguments.length === 1 ) {
268                         s = url;
269                         url = s ? s.url : undefined;
270                 }
271
272                 return jQuery.xhr().open( s ? s.type : undefined , url ).send( undefined , s );
273
274         },
275
276         // Serialize an array of form elements or a set of
277         // key/values into a query string
278         param: function( a, traditional ) {
279                 var s = [],
280                         add = function( key, value ) {
281                                 // If value is a function, invoke it and return its value
282                                 value = jQuery.isFunction(value) ? value() : value;
283                                 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
284                         };
285
286                 // Set traditional to true for jQuery <= 1.3.2 behavior.
287                 if ( traditional === undefined ) {
288                         traditional = jQuery.ajaxSettings.traditional;
289                 }
290
291                 // If an array was passed in, assume that it is an array of form elements.
292                 if ( jQuery.isArray(a) || a.jquery ) {
293                         // Serialize the form elements
294                         jQuery.each( a, function() {
295                                 add( this.name, this.value );
296                         });
297
298                 } else {
299                         // If traditional, encode the "old" way (the way 1.3.2 or older
300                         // did it), otherwise encode params recursively.
301                         for ( var prefix in a ) {
302                                 buildParams( prefix, a[prefix], traditional, add );
303                         }
304                 }
305
306                 // Return the resulting serialization
307                 return s.join("&").replace(r20, "+");
308         }
309 });
310
311 function buildParams( prefix, obj, traditional, add ) {
312         if ( jQuery.isArray(obj) && obj.length ) {
313                 // Serialize array item.
314                 jQuery.each( obj, function( i, v ) {
315                         if ( traditional || rbracket.test( prefix ) ) {
316                                 // Treat each array item as a scalar.
317                                 add( prefix, v );
318
319                         } else {
320                                 // If array item is non-scalar (array or object), encode its
321                                 // numeric index to resolve deserialization ambiguity issues.
322                                 // Note that rack (as of 1.0.0) can't currently deserialize
323                                 // nested arrays properly, and attempting to do so may cause
324                                 // a server error. Possible fixes are to modify rack's
325                                 // deserialization algorithm or to provide an option or flag
326                                 // to force array serialization to be shallow.
327                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
328                         }
329                 });
330
331         } else if ( !traditional && obj != null && typeof obj === "object" ) {
332                 // If we see an array here, it is empty and should be treated as an empty
333                 // object
334                 if ( jQuery.isArray( obj ) || jQuery.isEmptyObject( obj ) ) {
335                         add( prefix, "" );
336
337                 // Serialize object item.
338                 } else {
339                         jQuery.each( obj, function( k, v ) {
340                                 buildParams( prefix + "[" + k + "]", v, traditional, add );
341                         });
342                 }
343
344         } else {
345                 // Serialize scalar item.
346                 add( prefix, obj );
347         }
348 }
349
350 // This is still on the jQuery object... for now
351 // Want to move this to jQuery.ajax some day
352 jQuery.extend({
353
354         // Counter for holding the number of active queries
355         active: 0,
356
357         // Last-Modified header cache for next request
358         lastModified: {},
359         etag: {}
360
361 });
362
363 /*
364  * Create the request object; Microsoft failed to properly
365  * implement the XMLHttpRequest in IE7 (can't request local files),
366  * so we use the ActiveXObject when it is available
367  * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
368  * we need a fallback.
369  */
370 if ( window.ActiveXObject ) {
371         jQuery.ajaxSettings.xhr = function() {
372         if ( window.location.protocol !== "file:" ) {
373                 try {
374                         return new window.XMLHttpRequest();
375                 } catch( xhrError ) {}
376         }
377
378         try {
379                 return new window.ActiveXObject("Microsoft.XMLHTTP");
380         } catch( activeError ) {}
381         };
382 }
383
384 var testXHR = jQuery.ajaxSettings.xhr();
385
386 // Does this browser support XHR requests?
387 jQuery.support.ajax = !!testXHR;
388
389 // Does this browser support crossDomain XHR requests
390 jQuery.support.cors = testXHR && "withCredentials" in testXHR;
391
392 })( jQuery );