source: trunk/web/addons/job_monarch/lib/extjs/source/data/Connection.js @ 619

Last change on this file since 619 was 619, checked in by ramonb, 15 years ago

lib/:

  • added new AJAX dependancies: ExtJS, pChart, Lightbox2
File size: 21.8 KB
Line 
1/*
2 * Ext JS Library 2.2.1
3 * Copyright(c) 2006-2009, Ext JS, LLC.
4 * licensing@extjs.com
5 *
6 * http://extjs.com/license
7 */
8
9/**
10 * @class Ext.data.Connection
11 * @extends Ext.util.Observable
12 * <p>The class encapsulates a connection to the page's originating domain, allowing requests to be made
13 * either to a configured URL, or to a URL specified at request time.</p>
14 * <p>Requests made by this class are asynchronous, and will return immediately. No data from
15 * the server will be available to the statement immediately following the {@link #request} call.
16 * To process returned data, use a
17 * <a href="#request-option-success" ext:member="request-option-success" ext:cls="Ext.data.Connection">success callback</a>
18 * in the request options object,
19 * or an {@link #requestcomplete event listener}.</p>
20 * <p><h3>File Uploads</h3><a href="#request-option-isUpload" ext:member="request-option-isUpload" ext:cls="Ext.data.Connection">File uploads</a> are not performed using normal "Ajax" techniques, that
21 * is they are <b>not</b> performed using XMLHttpRequests. Instead the form is submitted in the standard
22 * manner with the DOM <tt>&lt;form></tt> element temporarily modified to have its
23 * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
24 * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
25 * but removed after the return data has been gathered.</p>
26 * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
27 * server is using JSON to send the return object, then the
28 * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
29 * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
30 * <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
31 * "&lt;" as "&amp;lt;", "&amp;" as "&amp;amp;" etc.</p>
32 * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
33 * is created containing a <tt>responseText</tt> property in order to conform to the
34 * requirements of event handlers and callbacks.</p>
35 * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
36 * and some server technologies (notably JEE) may require some custom processing in order to
37 * retrieve parameter names and parameter values from the packet content.</p>
38 * @constructor
39 * @param {Object} config a configuration object.
40 */
41Ext.data.Connection = function(config){
42    Ext.apply(this, config);
43    this.addEvents(
44        /**
45         * @event beforerequest
46         * Fires before a network request is made to retrieve a data object.
47         * @param {Connection} conn This Connection object.
48         * @param {Object} options The options config object passed to the {@link #request} method.
49         */
50        "beforerequest",
51        /**
52         * @event requestcomplete
53         * Fires if the request was successfully completed.
54         * @param {Connection} conn This Connection object.
55         * @param {Object} response The XHR object containing the response data.
56         * See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
57         * for details.
58         * @param {Object} options The options config object passed to the {@link #request} method.
59         */
60        "requestcomplete",
61        /**
62         * @event requestexception
63         * Fires if an error HTTP status was returned from the server.
64         * See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP Status Code Definitions</a>
65         * for details of HTTP status codes.
66         * @param {Connection} conn This Connection object.
67         * @param {Object} response The XHR object containing the response data.
68         * See <a href="http://www.w3.org/TR/XMLHttpRequest/">The XMLHttpRequest Object</a>
69         * for details.
70         * @param {Object} options The options config object passed to the {@link #request} method.
71         */
72        "requestexception"
73    );
74    Ext.data.Connection.superclass.constructor.call(this);
75};
76
77Ext.extend(Ext.data.Connection, Ext.util.Observable, {
78    /**
79     * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
80     */
81    /**
82     * @cfg {Object} extraParams (Optional) An object containing properties which are used as
83     * extra parameters to each request made by this object. (defaults to undefined)
84     */
85    /**
86     * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
87     *  to each request made by this object. (defaults to undefined)
88     */
89    /**
90     * @cfg {String} method (Optional) The default HTTP method to be used for requests.
91     * (defaults to undefined; if not set, but {@link #request} params are present, POST will be used;
92     * otherwise, GET will be used.)
93     */
94    /**
95     * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
96     */
97    timeout : 30000,
98    /**
99     * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
100     * @type Boolean
101     */
102    autoAbort:false,
103
104    /**
105     * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
106     * @type Boolean
107     */
108    disableCaching: true,
109   
110    /**
111     * @cfg {String} disableCachingParam (Optional) Change the parameter which is sent went disabling caching
112     * through a cache buster. Defaults to '_dc'
113     * @type String
114     */
115    disableCachingParam: '_dc',
116   
117
118    /**
119     * <p>Sends an HTTP request to a remote server.</p>
120     * <p><b>Important:</b> Ajax server requests are asynchronous, and this call will
121     * return before the response has been received. Process any returned data
122     * in a callback function.</p>
123     * <p>To execute a callback function in the correct scope, use the <tt>scope</tt> option.</p>
124     * @param {Object} options An object which may contain the following properties:<ul>
125     * <li><b>url</b> : String/Function (Optional)<div class="sub-desc">The URL to
126     * which to send the request, or a function to call which returns a URL string. The scope of the
127     * function is specified by the <tt>scope</tt> option. Defaults to configured URL.</div></li>
128     * <li><b>params</b> : Object/String/Function (Optional)<div class="sub-desc">
129     * An object containing properties which are used as parameters to the
130     * request, a url encoded string or a function to call to get either. The scope of the function
131     * is specified by the <tt>scope</tt> option.</div></li>
132     * <li><b>method</b> : String (Optional)<div class="sub-desc">The HTTP method to use
133     * for the request. Defaults to the configured method, or if no method was configured,
134     * "GET" if no parameters are being sent, and "POST" if parameters are being sent.  Note that
135     * the method name is case-sensitive and should be all caps.</div></li>
136     * <li><b>callback</b> : Function (Optional)<div class="sub-desc">The
137     * function to be called upon receipt of the HTTP response. The callback is
138     * called regardless of success or failure and is passed the following
139     * parameters:<ul>
140     * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
141     * <li><b>success</b> : Boolean<div class="sub-desc">True if the request succeeded.</div></li>
142     * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.
143     * See <a href="http://www.w3.org/TR/XMLHttpRequest/">http://www.w3.org/TR/XMLHttpRequest/</a> for details about
144     * accessing elements of the response.</div></li>
145     * </ul></div></li>
146     * <li><a id="request-option-success"></a><b>success</b> : Function (Optional)<div class="sub-desc">The function
147     * to be called upon success of the request. The callback is passed the following
148     * parameters:<ul>
149     * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li>
150     * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
151     * </ul></div></li>
152     * <li><b>failure</b> : Function (Optional)<div class="sub-desc">The function
153     * to be called upon failure of the request. The callback is passed the
154     * following parameters:<ul>
155     * <li><b>response</b> : Object<div class="sub-desc">The XMLHttpRequest object containing the response data.</div></li>
156     * <li><b>options</b> : Object<div class="sub-desc">The parameter to the request call.</div></li>
157     * </ul></div></li>
158     * <li><b>scope</b> : Object (Optional)<div class="sub-desc">The scope in
159     * which to execute the callbacks: The "this" object for the callback function. If the <tt>url</tt>, or <tt>params</tt> options were
160     * specified as functions from which to draw values, then this also serves as the scope for those function calls.
161     * Defaults to the browser window.</div></li>
162     * <li><b>form</b> : Element/HTMLElement/String (Optional)<div class="sub-desc">The <tt>&lt;form&gt;</tt>
163     * Element or the id of the <tt>&lt;form&gt;</tt> to pull parameters from.</div></li>
164     * <li><a id="request-option-isUpload"></a><b>isUpload</b> : Boolean (Optional)<div class="sub-desc"><b>Only meaningful when used
165     * with the <tt>form</tt> option.</b>
166     * <p>True if the form object is a file upload (will be set automatically if the form was
167     * configured with <b><tt>enctype</tt></b> "multipart/form-data").</p>
168     * <p>File uploads are not performed using normal "Ajax" techniques, that is they are <b>not</b>
169     * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
170     * DOM <tt>&lt;form></tt> element temporarily modified to have its
171     * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
172     * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
173     * but removed after the return data has been gathered.</p>
174     * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
175     * server is using JSON to send the return object, then the
176     * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
177     * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
178     * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
179     * is created containing a <tt>responseText</tt> property in order to conform to the
180     * requirements of event handlers and callbacks.</p>
181     * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
182     * and some server technologies (notably JEE) may require some custom processing in order to
183     * retrieve parameter names and parameter values from the packet content.</p>
184     * </div></li>
185     * <li><b>headers</b> : Object (Optional)<div class="sub-desc">Request
186     * headers to set for the request.</div></li>
187     * <li><b>xmlData</b> : Object (Optional)<div class="sub-desc">XML document
188     * to use for the post. Note: This will be used instead of params for the post
189     * data. Any params will be appended to the URL.</div></li>
190     * <li><b>jsonData</b> : Object/String (Optional)<div class="sub-desc">JSON
191     * data to use as the post. Note: This will be used instead of params for the post
192     * data. Any params will be appended to the URL.</div></li>
193     * <li><b>disableCaching</b> : Boolean (Optional)<div class="sub-desc">True
194     * to add a unique cache-buster param to GET requests.</div></li>
195     * </ul></p>
196     * <p>The options object may also contain any other property which might be needed to perform
197     * postprocessing in a callback because it is passed to callback functions.</p>
198     * @return {Number} transactionId The id of the server transaction. This may be used
199     * to cancel the request.
200     */
201    request : function(o){
202        if(this.fireEvent("beforerequest", this, o) !== false){
203            var p = o.params;
204
205            if(typeof p == "function"){
206                p = p.call(o.scope||window, o);
207            }
208            if(typeof p == "object"){
209                p = Ext.urlEncode(p);
210            }
211            if(this.extraParams){
212                var extras = Ext.urlEncode(this.extraParams);
213                p = p ? (p + '&' + extras) : extras;
214            }
215
216            var url = o.url || this.url;
217            if(typeof url == 'function'){
218                url = url.call(o.scope||window, o);
219            }
220
221            if(o.form){
222                var form = Ext.getDom(o.form);
223                url = url || form.action;
224
225                var enctype = form.getAttribute("enctype");
226                if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
227                    return this.doFormUpload(o, p, url);
228                }
229                var f = Ext.lib.Ajax.serializeForm(form);
230                p = p ? (p + '&' + f) : f;
231            }
232
233            var hs = o.headers;
234            if(this.defaultHeaders){
235                hs = Ext.apply(hs || {}, this.defaultHeaders);
236                if(!o.headers){
237                    o.headers = hs;
238                }
239            }
240
241            var cb = {
242                success: this.handleResponse,
243                failure: this.handleFailure,
244                scope: this,
245                argument: {options: o},
246                timeout : o.timeout || this.timeout
247            };
248
249            var method = o.method||this.method||((p || o.xmlData || o.jsonData) ? "POST" : "GET");
250
251            if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
252                var dcp = o.disableCachingParam || this.disableCachingParam;
253                url += (url.indexOf('?') != -1 ? '&' : '?') + dcp + '=' + (new Date().getTime());
254            }
255
256            if(typeof o.autoAbort == 'boolean'){ // options gets top priority
257                if(o.autoAbort){
258                    this.abort();
259                }
260            }else if(this.autoAbort !== false){
261                this.abort();
262            }
263            if((method == 'GET' || o.xmlData || o.jsonData) && p){
264                url += (url.indexOf('?') != -1 ? '&' : '?') + p;
265                p = '';
266            }
267            this.transId = Ext.lib.Ajax.request(method, url, cb, p, o);
268            return this.transId;
269        }else{
270            Ext.callback(o.callback, o.scope, [o, null, null]);
271            return null;
272        }
273    },
274
275    /**
276     * Determine whether this object has a request outstanding.
277     * @param {Number} transactionId (Optional) defaults to the last transaction
278     * @return {Boolean} True if there is an outstanding request.
279     */
280    isLoading : function(transId){
281        if(transId){
282            return Ext.lib.Ajax.isCallInProgress(transId);
283        }else{
284            return this.transId ? true : false;
285        }
286    },
287
288    /**
289     * Aborts any outstanding request.
290     * @param {Number} transactionId (Optional) defaults to the last transaction
291     */
292    abort : function(transId){
293        if(transId || this.isLoading()){
294            Ext.lib.Ajax.abort(transId || this.transId);
295        }
296    },
297
298    // private
299    handleResponse : function(response){
300        this.transId = false;
301        var options = response.argument.options;
302        response.argument = options ? options.argument : null;
303        this.fireEvent("requestcomplete", this, response, options);
304        Ext.callback(options.success, options.scope, [response, options]);
305        Ext.callback(options.callback, options.scope, [options, true, response]);
306    },
307
308    // private
309    handleFailure : function(response, e){
310        this.transId = false;
311        var options = response.argument.options;
312        response.argument = options ? options.argument : null;
313        this.fireEvent("requestexception", this, response, options, e);
314        Ext.callback(options.failure, options.scope, [response, options]);
315        Ext.callback(options.callback, options.scope, [options, false, response]);
316    },
317
318    // private
319    doFormUpload : function(o, ps, url){
320        var id = Ext.id();
321        var frame = document.createElement('iframe');
322        frame.id = id;
323        frame.name = id;
324        frame.className = 'x-hidden';
325        if(Ext.isIE){
326            frame.src = Ext.SSL_SECURE_URL;
327        }
328        document.body.appendChild(frame);
329
330        if(Ext.isIE){
331           document.frames[id].name = id;
332        }
333
334        var form = Ext.getDom(o.form);
335        form.target = id;
336        form.method = 'POST';
337        form.enctype = form.encoding = 'multipart/form-data';
338        if(url){
339            form.action = url;
340        }
341
342        var hiddens, hd;
343        if(ps){ // add dynamic params
344            hiddens = [];
345            ps = Ext.urlDecode(ps, false);
346            for(var k in ps){
347                if(ps.hasOwnProperty(k)){
348                    hd = document.createElement('input');
349                    hd.type = 'hidden';
350                    hd.name = k;
351                    hd.value = ps[k];
352                    form.appendChild(hd);
353                    hiddens.push(hd);
354                }
355            }
356        }
357
358        function cb(){
359            var r = {  // bogus response object
360                responseText : '',
361                responseXML : null
362            };
363
364            r.argument = o ? o.argument : null;
365
366            try { //
367                var doc;
368                if(Ext.isIE){
369                    doc = frame.contentWindow.document;
370                }else {
371                    doc = (frame.contentDocument || window.frames[id].document);
372                }
373                if(doc && doc.body){
374                    r.responseText = doc.body.innerHTML;
375                }
376                if(doc && doc.XMLDocument){
377                    r.responseXML = doc.XMLDocument;
378                }else {
379                    r.responseXML = doc;
380                }
381            }
382            catch(e) {
383                // ignore
384            }
385
386            Ext.EventManager.removeListener(frame, 'load', cb, this);
387
388            this.fireEvent("requestcomplete", this, r, o);
389
390            Ext.callback(o.success, o.scope, [r, o]);
391            Ext.callback(o.callback, o.scope, [o, true, r]);
392
393            setTimeout(function(){Ext.removeNode(frame);}, 100);
394        }
395
396        Ext.EventManager.on(frame, 'load', cb, this);
397        form.submit();
398
399        if(hiddens){ // remove dynamic params
400            for(var i = 0, len = hiddens.length; i < len; i++){
401                Ext.removeNode(hiddens[i]);
402            }
403        }
404    }
405});
406
407/**
408 * @class Ext.Ajax
409 * @extends Ext.data.Connection
410 * Global Ajax request class.  Provides a simple way to make Ajax requests with maximum flexibility.  Example usage:
411 * <pre><code>
412// Basic request
413Ext.Ajax.request({
414   url: 'foo.php',
415   success: someFn,
416   failure: otherFn,
417   headers: {
418       'my-header': 'foo'
419   },
420   params: { foo: 'bar' }
421});
422
423// Simple ajax form submission
424Ext.Ajax.request({
425    form: 'some-form',
426    params: 'foo=bar'
427});
428
429// Default headers to pass in every request
430Ext.Ajax.defaultHeaders = {
431    'Powered-By': 'Ext'
432};
433
434// Global Ajax events can be handled on every request!
435Ext.Ajax.on('beforerequest', this.showSpinner, this);
436</code></pre>
437 * @singleton
438 */
439Ext.Ajax = new Ext.data.Connection({
440    /**
441     * @cfg {String} url @hide
442     */
443    /**
444     * @cfg {Object} extraParams @hide
445     */
446    /**
447     * @cfg {Object} defaultHeaders @hide
448     */
449    /**
450     * @cfg {String} method (Optional) @hide
451     */
452    /**
453     * @cfg {Number} timeout (Optional) @hide
454     */
455    /**
456     * @cfg {Boolean} autoAbort (Optional) @hide
457     */
458
459    /**
460     * @cfg {Boolean} disableCaching (Optional) @hide
461     */
462
463    /**
464     * @property  disableCaching
465     * True to add a unique cache-buster param to GET requests. (defaults to true)
466     * @type Boolean
467     */
468    /**
469     * @property  url
470     * The default URL to be used for requests to the server. (defaults to undefined)
471     * @type String
472     */
473    /**
474     * @property  extraParams
475     * An object containing properties which are used as
476     * extra parameters to each request made by this object. (defaults to undefined)
477     * @type Object
478     */
479    /**
480     * @property  defaultHeaders
481     * An object containing request headers which are added to each request made by this object. (defaults to undefined)
482     * @type Object
483     */
484    /**
485     * @property  method
486     * The default HTTP method to be used for requests. Note that this is case-sensitive and should be all caps (defaults
487     * to undefined; if not set but parms are present will use "POST," otherwise "GET.")
488     * @type String
489     */
490    /**
491     * @property  timeout
492     * The timeout in milliseconds to be used for requests. (defaults to 30000)
493     * @type Number
494     */
495
496    /**
497     * @property  autoAbort
498     * Whether a new request should abort any pending requests. (defaults to false)
499     * @type Boolean
500     */
501    autoAbort : false,
502
503    /**
504     * Serialize the passed form into a url encoded string
505     * @param {String/HTMLElement} form
506     * @return {String}
507     */
508    serializeForm : function(form){
509        return Ext.lib.Ajax.serializeForm(form);
510    }
511});
Note: See TracBrowser for help on using the repository browser.