Implemented a better error handling for ajax requests. Exceptions caused by dropping...
[jquery.git] / src / ajax / ajax.js
1 jQuery.fn.extend({
2
3         /**
4          * Load HTML from a remote file and inject it into the DOM, only if it's
5          * been modified by the server.
6          *
7          * @example $("#feeds").loadIfModified("feeds.html");
8          * @before <div id="feeds"></div>
9          * @result <div id="feeds"><b>45</b> feeds found.</div>
10          *
11          * @name loadIfModified
12          * @type jQuery
13          * @param String url The URL of the HTML file to load.
14          * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
15          * @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
16          * @cat AJAX
17          */
18         loadIfModified: function( url, params, callback ) {
19                 this.load( url, params, callback, 1 );
20         },
21
22         /**
23          * Load HTML from a remote file and inject it into the DOM.
24          *
25          * @example $("#feeds").load("feeds.html");
26          * @before <div id="feeds"></div>
27          * @result <div id="feeds"><b>45</b> feeds found.</div>
28          *
29          * @example $("#feeds").load("feeds.html",
30          *   {limit: 25},
31          *   function() { alert("The last 25 entries in the feed have been loaded"); }
32          * );
33          * @desc Same as above, but with an additional parameter
34          * and a callback that is executed when the data was loaded.
35          *
36          * @name load
37          * @type jQuery
38          * @param String url The URL of the HTML file to load.
39          * @param Object params (optional) A set of key/value pairs that will be sent as data to the server.
40          * @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
41          * @cat AJAX
42          */
43         load: function( url, params, callback, ifModified ) {
44                 if ( url.constructor == Function )
45                         return this.bind("load", url);
46
47                 callback = callback || function(){};
48
49                 // Default to a GET request
50                 var type = "GET";
51
52                 // If the second parameter was provided
53                 if ( params ) {
54                         // If it's a function
55                         if ( params.constructor == Function ) {
56                                 // We assume that it's the callback
57                                 callback = params;
58                                 params = null;
59
60                         // Otherwise, build a param string
61                         } else {
62                                 params = jQuery.param( params );
63                                 type = "POST";
64                         }
65                 }
66
67                 var self = this;
68
69                 // Request the remote document
70                 jQuery.ajax({
71                         url: url,
72                         type: type,
73                         data: params,
74                         ifModified: ifModified,
75                         complete: function(res, status){
76                                 if ( status == "success" || !ifModified && status == "notmodified" ) {
77                                         // Inject the HTML into all the matched elements
78                                         self.html(res.responseText)
79                                           // Execute all the scripts inside of the newly-injected HTML
80                                           .evalScripts()
81                                           // Execute callback
82                                           .each( callback, [res.responseText, status, res] );
83                                 } else
84                                         callback.apply( self, [res.responseText, status, res] );
85                         }
86                 });
87                 return this;
88         },
89
90         /**
91          * Serializes a set of input elements into a string of data.
92          * This will serialize all given elements.
93          *
94          * A serialization similar to the form submit of a browser is
95          * provided by the form plugin. It also takes multiple-selects 
96          * into account, while this method recognizes only a single option.
97          *
98          * @example $("input[@type=text]").serialize();
99          * @before <input type='text' name='name' value='John'/>
100          * <input type='text' name='location' value='Boston'/>
101          * @after name=John&location=Boston
102          * @desc Serialize a selection of input elements to a string
103          *
104          * @name serialize
105          * @type String
106          * @cat AJAX
107          */
108         serialize: function() {
109                 return jQuery.param( this );
110         },
111
112         /**
113          * Evaluate all script tags inside this jQuery. If they have a src attribute,
114          * the script is loaded, otherwise it's content is evaluated.
115          *
116          * @name evalScripts
117          * @type jQuery
118          * @private
119          * @cat AJAX
120          */
121         evalScripts: function() {
122                 return this.find('script').each(function(){
123                         if ( this.src )
124                                 jQuery.getScript( this.src );
125                         else {
126                                 jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" );
127                         }
128                 }).end();
129         }
130
131 });
132
133 // If IE is used, create a wrapper for the XMLHttpRequest object
134 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
135         XMLHttpRequest = function(){
136                 return new ActiveXObject("Microsoft.XMLHTTP");
137         };
138
139 // Attach a bunch of functions for handling common AJAX events
140
141 /**
142  * Attach a function to be executed whenever an AJAX request begins
143  * and there is none already active.
144  *
145  * @example $("#loading").ajaxStart(function(){
146  *   $(this).show();
147  * });
148  * @desc Show a loading message whenever an AJAX request starts
149  * (and none is already active).
150  *
151  * @name ajaxStart
152  * @type jQuery
153  * @param Function callback The function to execute.
154  * @cat AJAX
155  */
156
157 /**
158  * Attach a function to be executed whenever all AJAX requests have ended.
159  *
160  * @example $("#loading").ajaxStop(function(){
161  *   $(this).hide();
162  * });
163  * @desc Hide a loading message after all the AJAX requests have stopped.
164  *
165  * @name ajaxStop
166  * @type jQuery
167  * @param Function callback The function to execute.
168  * @cat AJAX
169  */
170
171 /**
172  * Attach a function to be executed whenever an AJAX request completes.
173  *
174  * The XMLHttpRequest and settings used for that request are passed
175  * as arguments to the callback.
176  *
177  * @example $("#msg").ajaxComplete(function(request, settings){
178  *   $(this).append("<li>Request Complete.</li>");
179  * });
180  * @desc Show a message when an AJAX request completes.
181  *
182  * @name ajaxComplete
183  * @type jQuery
184  * @param Function callback The function to execute.
185  * @cat AJAX
186  */
187
188 /**
189  * Attach a function to be executed whenever an AJAX request completes
190  * successfully.
191  *
192  * The XMLHttpRequest and settings used for that request are passed
193  * as arguments to the callback.
194  *
195  * @example $("#msg").ajaxSuccess(function(request, settings){
196  *   $(this).append("<li>Successful Request!</li>");
197  * });
198  * @desc Show a message when an AJAX request completes successfully.
199  *
200  * @name ajaxSuccess
201  * @type jQuery
202  * @param Function callback The function to execute.
203  * @cat AJAX
204  */
205
206 /**
207  * Attach a function to be executed whenever an AJAX request fails.
208  *
209  * The XMLHttpRequest and settings used for that request are passed
210  * as arguments to the callback. A third argument, an exception object,
211  * is passed if an exception occured while processing the request.
212  *
213  * @example $("#msg").ajaxError(function(request, settings){
214  *   $(this).append("<li>Error requesting page " + settings.url + "</li>");
215  * });
216  * @desc Show a message when an AJAX request fails.
217  *
218  * @name ajaxError
219  * @type jQuery
220  * @param Function callback The function to execute.
221  * @cat AJAX
222  */
223  
224 /**
225  * Attach a function to be executed before an AJAX request is send.
226  *
227  * The XMLHttpRequest and settings used for that request are passed
228  * as arguments to the callback.
229  *
230  * @example $("#msg").ajaxSend(function(request, settings){
231  *   $(this).append("<li>Starting request at " + settings.url + "</li>");
232  * });
233  * @desc Show a message before an AJAX request is send.
234  *
235  * @name ajaxSend
236  * @type jQuery
237  * @param Function callback The function to execute.
238  * @cat AJAX
239  */
240
241 new function(){
242         var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(",");
243
244         for ( var i = 0; i < e.length; i++ ) new function(){
245                 var o = e[i];
246                 jQuery.fn[o] = function(f){
247                         return this.bind(o, f);
248                 };
249         };
250 };
251
252 jQuery.extend({
253
254         /**
255          * Load a remote page using an HTTP GET request.
256          *
257          * @example $.get("test.cgi");
258          *
259          * @example $.get("test.cgi", { name: "John", time: "2pm" } );
260          *
261          * @example $.get("test.cgi", function(data){
262          *   alert("Data Loaded: " + data);
263          * });
264          *
265          * @example $.get("test.cgi",
266          *   { name: "John", time: "2pm" },
267          *   function(data){
268          *     alert("Data Loaded: " + data);
269          *   }
270          * );
271          *
272          * @name $.get
273          * @type XMLHttpRequest
274          * @param String url The URL of the page to load.
275          * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
276          * @param Function callback (optional) A function to be executed whenever the data is loaded.
277          * @cat AJAX
278          */
279         get: function( url, data, callback, type, ifModified ) {
280                 // shift arguments if data argument was ommited
281                 if ( data && data.constructor == Function ) {
282                         callback = data;
283                         data = null;
284                 }
285                 return jQuery.ajax({
286                         url: url,
287                         data: data,
288                         success: callback,
289                         dataType: type,
290                         ifModified: ifModified
291                 });
292         },
293
294         /**
295          * Load a remote page using an HTTP GET request, only if it hasn't
296          * been modified since it was last retrieved.
297          *
298          * @example $.getIfModified("test.html");
299          *
300          * @example $.getIfModified("test.html", { name: "John", time: "2pm" } );
301          *
302          * @example $.getIfModified("test.cgi", function(data){
303          *   alert("Data Loaded: " + data);
304          * });
305          *
306          * @example $.getifModified("test.cgi",
307          *   { name: "John", time: "2pm" },
308          *   function(data){
309          *     alert("Data Loaded: " + data);
310          *   }
311          * );
312          *
313          * @name $.getIfModified
314          * @type XMLHttpRequest
315          * @param String url The URL of the page to load.
316          * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
317          * @param Function callback (optional) A function to be executed whenever the data is loaded.
318          * @cat AJAX
319          */
320         getIfModified: function( url, data, callback, type ) {
321                 return jQuery.get(url, data, callback, type, 1);
322         },
323
324         /**
325          * Loads, and executes, a remote JavaScript file using an HTTP GET request.
326          *
327          * Warning: Safari <= 2.0.x is unable to evalulate scripts in a global
328          * context synchronously. If you load functions via getScript, make sure
329          * to call them after a delay.
330          *
331          * @example $.getScript("test.js");
332          *
333          * @example $.getScript("test.js", function(){
334          *   alert("Script loaded and executed.");
335          * });
336          *
337          * @name $.getScript
338          * @type XMLHttpRequest
339          * @param String url The URL of the page to load.
340          * @param Function callback (optional) A function to be executed whenever the data is loaded.
341          * @cat AJAX
342          */
343         getScript: function( url, callback ) {
344                 return jQuery.get(url, null, callback, "script");
345         },
346
347         /**
348          * Load JSON data using an HTTP GET request.
349          *
350          * @example $.getJSON("test.js", function(json){
351          *   alert("JSON Data: " + json.users[3].name);
352          * });
353          *
354          * @example $.getJSON("test.js",
355          *   { name: "John", time: "2pm" },
356          *   function(json){
357          *     alert("JSON Data: " + json.users[3].name);
358          *   }
359          * );
360          *
361          * @name $.getJSON
362          * @type XMLHttpRequest
363          * @param String url The URL of the page to load.
364          * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
365          * @param Function callback A function to be executed whenever the data is loaded.
366          * @cat AJAX
367          */
368         getJSON: function( url, data, callback ) {
369                 return jQuery.get(url, data, callback, "json");
370         },
371
372         /**
373          * Load a remote page using an HTTP POST request.
374          *
375          * @example $.post("test.cgi");
376          *
377          * @example $.post("test.cgi", { name: "John", time: "2pm" } );
378          *
379          * @example $.post("test.cgi", function(data){
380          *   alert("Data Loaded: " + data);
381          * });
382          *
383          * @example $.post("test.cgi",
384          *   { name: "John", time: "2pm" },
385          *   function(data){
386          *     alert("Data Loaded: " + data);
387          *   }
388          * );
389          *
390          * @name $.post
391          * @type XMLHttpRequest
392          * @param String url The URL of the page to load.
393          * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
394          * @param Function callback (optional) A function to be executed whenever the data is loaded.
395          * @cat AJAX
396          */
397         post: function( url, data, callback, type ) {
398                 return jQuery.ajax({
399                         type: "POST",
400                         url: url,
401                         data: data,
402                         success: callback,
403                         dataType: type
404                 });
405         },
406
407         // timeout (ms)
408         timeout: 0,
409
410         /**
411          * Set the timeout of all AJAX requests to a specific amount of time.
412          * This will make all future AJAX requests timeout after a specified amount
413          * of time.
414          *
415          * Set to null or 0 to disable timeouts (default).
416          *
417          * You can manually abort requests with the XMLHttpRequest's (returned by
418          * all ajax functions) abort() method.
419          *
420          * @example $.ajaxTimeout( 5000 );
421          * @desc Make all AJAX requests timeout after 5 seconds.
422          *
423          * @name $.ajaxTimeout
424          * @type undefined
425          * @param Number time How long before an AJAX request times out.
426          * @cat AJAX
427          */
428         ajaxTimeout: function(timeout) {
429                 jQuery.timeout = timeout;
430         },
431
432         // Last-Modified header cache for next request
433         lastModified: {},
434
435         /**
436          * Load a remote page using an HTTP request.
437          *
438          * This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for
439          * higher-level abstractions.
440          *
441          * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
442          * need that object to manipulate directly, but it is available if you need to
443          * abort the request manually.
444          *
445          * Note: Make sure the server sends the right mimetype (eg. xml as
446          * "text/xml"). Sending the wrong mimetype will get you into serious
447          * trouble that jQuery can't solve.
448          *
449          * Supported datatypes are (see dataType option):
450          *
451          * "xml": Returns a XML document that can be processed via jQuery.
452          *
453          * "html": Returns HTML as plain text, included script tags are evaluated.
454          *
455          * "script": Evaluates the response as Javascript and returns it as plain text.
456          *
457          * "json": Evaluates the response as JSON and returns a Javascript Object
458          *
459          * $.ajax() takes one argument, an object of key/value pairs, that are
460          * used to initalize and handle the request. These are all the key/values that can
461          * be used:
462          *
463          * (String) url - The URL to request.
464          *
465          * (String) type - The type of request to make ("POST" or "GET"), default is "GET".
466          *
467          * (String) dataType - The type of data that you're expecting back from
468          * the server. No default: If the server sends xml, the responseXML, otherwise
469          * the responseText is passed to the success callback.
470          *
471          * (Boolean) ifModified - Allow the request to be successful only if the
472          * response has changed since the last request. This is done by checking the
473          * Last-Modified header. Default value is false, ignoring the header.
474          *
475          * (Number) timeout - Local timeout to override global timeout, eg. to give a
476          * single request a longer timeout while all others timeout after 1 seconds.
477          * See $.ajaxTimeout() for global timeouts.
478          *
479          * (Boolean) global - Whether to trigger global AJAX event handlers for
480          * this request, default is true. Set to false to prevent that global handlers
481          * like ajaxStart or ajaxStop are triggered.
482          *
483          * (Function) error - A function to be called if the request fails. The
484          * function gets passed tree arguments: The XMLHttpRequest object, a
485          * string describing the type of error that occurred and an optional
486          * exception object, if one occured.
487          *
488          * (Function) success - A function to be called if the request succeeds. The
489          * function gets passed one argument: The data returned from the server,
490          * formatted according to the 'dataType' parameter.
491          *
492          * (Function) complete - A function to be called when the request finishes. The
493          * function gets passed two arguments: The XMLHttpRequest object and a
494          * string describing the type of success of the request.
495          *
496          * (Object|String) data - Data to be sent to the server. Converted to a query
497          * string, if not already a string. Is appended to the url for GET-requests.
498          * See processData option to prevent this automatic processing.
499          *
500          * (String) contentType - When sending data to the server, use this content-type.
501          * Default is "application/x-www-form-urlencoded", which is fine for most cases.
502          *
503          * (Boolean) processData - By default, data passed in to the data option as an object
504          * other as string will be processed and transformed into a query string, fitting to
505          * the default content-type "application/x-www-form-urlencoded". If you want to send
506          * DOMDocuments, set this option to false.
507          *
508          * (Boolean) async - By default, all requests are send asynchronous (set to true).
509          * If you need synchronous requests, set this option to false.
510          *
511          * (Function) beforeSend - A pre-callback to set custom headers etc., the
512          * XMLHttpRequest is passed as the only argument.
513          *
514          * @example $.ajax({
515          *   type: "GET",
516          *   url: "test.js",
517          *   dataType: "script"
518          * })
519          * @desc Load and execute a JavaScript file.
520          *
521          * @example $.ajax({
522          *   type: "POST",
523          *   url: "some.php",
524          *   data: "name=John&location=Boston",
525          *   success: function(msg){
526          *     alert( "Data Saved: " + msg );
527          *   }
528          * });
529          * @desc Save some data to the server and notify the user once its complete.
530          *
531          * @example var html = $.ajax({
532          *  url: "some.php",
533          *  async: false
534          * }).responseText;
535          * @desc Loads data synchronously. Blocks the browser while the requests is active.
536          * It is better to block user interaction with others means when synchronization is
537          * necessary, instead to block the complete browser.
538          *
539          * @example var xmlDocument = [create xml document];
540          * $.ajax({
541          *   url: "page.php",
542          *   processData: false,
543          *   data: xmlDocument,
544          *   success: handleResponse
545          * });
546          * @desc Sends an xml document as data to the server. By setting the processData
547          * option to false, the automatic conversion of data to strings is prevented.
548          * 
549          * @name $.ajax
550          * @type XMLHttpRequest
551          * @param Hash prop A set of properties to initialize the request with.
552          * @cat AJAX
553          */
554         ajax: function( s ) {
555                 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
556                 s = jQuery.extend({
557                         global: true,
558                         ifModified: false,
559                         type: "GET",
560                         timeout: jQuery.timeout,
561                         complete: null,
562                         success: null,
563                         error: null,
564                         dataType: null,
565                         url: null,
566                         data: null,
567                         contentType: "application/x-www-form-urlencoded",
568                         processData: true,
569                         async: true,
570                         beforeSend: null
571                 }, s);
572
573                 // if data available
574                 if ( s.data ) {
575                         // convert data if not already a string
576                         if (s.processData && typeof s.data != 'string')
577                         s.data = jQuery.param(s.data);
578                         // append data to url for get requests
579                         if( s.type.toLowerCase() == "get" )
580                                 // "?" + data or "&" + data (in case there are already params)
581                                 s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
582                 }
583
584                 // Watch for a new set of requests
585                 if ( s.global && ! jQuery.active++ )
586                         jQuery.event.trigger( "ajaxStart" );
587
588                 var requestDone = false;
589
590                 // Create the request object
591                 var xml = new XMLHttpRequest();
592
593                 // Open the socket
594                 xml.open(s.type, s.url, s.async);
595
596                 // Set the correct header, if data is being sent
597                 if ( s.data )
598                         xml.setRequestHeader("Content-Type", s.contentType);
599
600                 // Set the If-Modified-Since header, if ifModified mode.
601                 if ( s.ifModified )
602                         xml.setRequestHeader("If-Modified-Since",
603                                 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
604
605                 // Set header so the called script knows that it's an XMLHttpRequest
606                 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
607
608                 // Make sure the browser sends the right content length
609                 if ( xml.overrideMimeType )
610                         xml.setRequestHeader("Connection", "close");
611                         
612                 // Allow custom headers/mimetypes
613                 if( s.beforeSend )
614                         s.beforeSend(xml);
615                 if (s.global)
616                     jQuery.event.trigger("ajaxSend", [xml, s]);
617
618                 // Wait for a response to come back
619                 var onreadystatechange = function(isTimeout){
620                         // The transfer is complete and the data is available, or the request timed out
621                         if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
622                                 requestDone = true;
623                                 var status;
624                                 try {
625                                         status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
626                                                 s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
627                                         // Make sure that the request was successful or notmodified
628                                         if ( status != "error" ) {
629                                                 // Cache Last-Modified header, if ifModified mode.
630                                                 var modRes;
631                                                 try {
632                                                         modRes = xml.getResponseHeader("Last-Modified");
633                                                 } catch(e) {} // swallow exception thrown by FF if header is not available
634         
635                                                 if ( s.ifModified && modRes )
636                                                         jQuery.lastModified[s.url] = modRes;
637         
638                                                 // process the data (runs the xml through httpData regardless of callback)
639                                                 var data = jQuery.httpData( xml, s.dataType );
640         
641                                                 // If a local callback was specified, fire it and pass it the data
642                                                 if ( s.success )
643                                                         s.success( data, status );
644         
645                                                 // Fire the global callback
646                                                 if( s.global )
647                                                         jQuery.event.trigger( "ajaxSuccess", [xml, s] );
648                                         }
649                                 } catch(e) {
650                                         status = "error";
651                                         jQuery.handleError(s, xml, status, e);
652                                 }
653
654                                 // The request was completed
655                                 if( s.global )
656                                         jQuery.event.trigger( "ajaxComplete", [xml, s] );
657
658                                 // Handle the global AJAX counter
659                                 if ( s.global && ! --jQuery.active )
660                                         jQuery.event.trigger( "ajaxStop" );
661
662                                 // Process result
663                                 if ( s.complete ) s.complete(xml, status);
664
665                                 // Stop memory leaks
666                                 xml.onreadystatechange = function(){};
667                                 xml = null;
668                         }
669                 };
670                 xml.onreadystatechange = onreadystatechange;
671
672                 // Timeout checker
673                 if(s.timeout > 0)
674                         setTimeout(function(){
675                                 // Check to see if the request is still happening
676                                 if (xml) {
677                                         // Cancel the request
678                                         xml.abort();
679
680                                         if ( !requestDone ) onreadystatechange( "timeout" );
681
682                                         // Clear from memory
683                                         xml = null;
684                                 }
685                         }, s.timeout);
686                         
687                 // save non-leaking reference 
688                 var xml2 = xml;
689
690                 // Send the data
691                 try {
692                         xml2.send(s.data);
693                 } catch(e) {
694                         jQuery.handleError(s, xml, null, e);
695                 }
696                 
697                 // return XMLHttpRequest to allow aborting the request etc.
698                 return xml2;
699         },
700
701         handleError: function(s, xml, status, e) {
702                 // If a local callback was specified, fire it
703                 if ( s.error ) s.error( xml, status, e );
704
705                 // Fire the global callback
706                 if( s.global )
707                         jQuery.event.trigger( "ajaxError", [xml, s, e] );
708         },
709
710         // Counter for holding the number of active queries
711         active: 0,
712
713         // Determines if an XMLHttpRequest was successful or not
714         httpSuccess: function(r) {
715                 return !r.status && location.protocol == "file:" ||
716                         ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
717                         jQuery.browser.safari && r.status == undefined;
718         },
719
720         // Determines if an XMLHttpRequest returns NotModified
721         httpNotModified: function(xml, url) {
722                 var xmlRes = xml.getResponseHeader("Last-Modified");
723
724                 // Firefox always returns 200. check Last-Modified date
725                 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
726                         jQuery.browser.safari && xml.status == undefined;
727         },
728
729         /* Get the data out of an XMLHttpRequest.
730          * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
731          * otherwise return plain text.
732          * (String) data - The type of data that you're expecting back,
733          * (e.g. "xml", "html", "script")
734          */
735         httpData: function(r,type) {
736                 var ct = r.getResponseHeader("content-type");
737                 var data = !type && ct && ct.indexOf("xml") >= 0;
738                 data = type == "xml" || data ? r.responseXML : r.responseText;
739
740                 // If the type is "script", eval it in global context
741                 if ( type == "script" ) {
742                         jQuery.globalEval( data );
743                 }
744
745                 // Get the JavaScript object, if JSON is used.
746                 if ( type == "json" ) eval( "data = " + data );
747
748                 // evaluate scripts within html
749                 if ( type == "html" ) jQuery("<div>").html(data).evalScripts();
750
751                 return data;
752         },
753
754         // Serialize an array of form elements or a set of
755         // key/values into a query string
756         param: function(a) {
757                 var s = [];
758
759                 // If an array was passed in, assume that it is an array
760                 // of form elements
761                 if ( a.constructor == Array || a.jquery ) {
762                         // Serialize the form elements
763                         for ( var i = 0; i < a.length; i++ )
764                                 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
765
766                 // Otherwise, assume that it's an object of key/value pairs
767                 } else {
768                         // Serialize the key/values
769                         for ( var j in a ) {
770                                 // If the value is an array then the key names need to be repeated
771                                 if( a[j].constructor == Array ) {
772                                         for (var k = 0; k < a[j].length; k++) {
773                                                 s.push( j + "=" + encodeURIComponent( a[j][k] ) );
774                                         }
775                                 } else {
776                                         s.push( j + "=" + encodeURIComponent( a[j] ) );
777                                 }
778                         }
779                 }
780
781                 // Return the resulting serialization
782                 return s.join("&");
783         },
784         
785         // evalulates a script in global context
786         // not reliable for safari
787         globalEval: function(data) {
788                 if (window.execScript)
789                         window.execScript( data );
790                 else if(jQuery.browser.safari)
791                         // safari doesn't provide a synchronous global eval
792                         window.setTimeout( data, 0 );
793                 else
794                         eval.call( window, data );
795         }
796
797 });