7368844678a7daf3b701f0fb19f548580631602f
[roojs1] / Roo / data / Connection.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12  
13
14 /**
15  * @class Roo.data.Connection
16  * @extends Roo.util.Observable
17  * The class encapsulates a connection to the page's originating domain, allowing requests to be made
18  * either to a configured URL, or to a URL specified at request time. 
19  * 
20  * Requests made by this class are asynchronous, and will return immediately. No data from
21  * the server will be available to the statement immediately following the {@link #request} call.
22  * To process returned data, use a callback in the request options object, or an event listener.
23  * 
24  * Note: If you are doing a file upload, you will not get a normal response object sent back to
25  * your callback or event handler.  Since the upload is handled via in IFRAME, there is no XMLHttpRequest.
26  * The response object is created using the innerHTML of the IFRAME's document as the responseText
27  * property and, if present, the IFRAME's XML document as the responseXML property.
28  * 
29  * This means that a valid XML or HTML document must be returned. If JSON data is required, it is suggested
30  * that it be placed either inside a &lt;textarea> in an HTML document and retrieved from the responseText
31  * using a regex, or inside a CDATA section in an XML document and retrieved from the responseXML using
32  * standard DOM methods.
33  * @constructor
34  * @param {Object} config a configuration object.
35  */
36 Roo.data.Connection = function(config){
37     Roo.apply(this, config);
38     this.addEvents({
39         /**
40          * @event beforerequest
41          * Fires before a network request is made to retrieve a data object.
42          * @param {Connection} conn This Connection object.
43          * @param {Object} options The options config object passed to the {@link #request} method.
44          */
45         "beforerequest" : true,
46         /**
47          * @event requestcomplete
48          * Fires if the request was successfully completed.
49          * @param {Connection} conn This Connection object.
50          * @param {Object} response The XHR object containing the response data.
51          * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
52          * @param {Object} options The options config object passed to the {@link #request} method.
53          */
54         "requestcomplete" : true,
55         /**
56          * @event requestexception
57          * Fires if an error HTTP status was returned from the server.
58          * See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html} for details of HTTP status codes.
59          * @param {Connection} conn This Connection object.
60          * @param {Object} response The XHR object containing the response data.
61          * See {@link http://www.w3.org/TR/XMLHttpRequest/} for details.
62          * @param {Object} options The options config object passed to the {@link #request} method.
63          */
64         "requestexception" : true
65     });
66     Roo.data.Connection.superclass.constructor.call(this);
67 };
68
69 Roo.extend(Roo.data.Connection, Roo.util.Observable, {
70     /**
71      * @cfg {String} url (Optional) The default URL to be used for requests to the server. (defaults to undefined)
72      */
73     /**
74      * @cfg {Object} extraParams (Optional) An object containing properties which are used as
75      * extra parameters to each request made by this object. (defaults to undefined)
76      */
77     /**
78      * @cfg {Object} defaultHeaders (Optional) An object containing request headers which are added
79      *  to each request made by this object. (defaults to undefined)
80      */
81     /**
82      * @cfg {String} method (Optional) The default HTTP method to be used for requests. (defaults to undefined; if not set but parms are present will use POST, otherwise GET)
83      */
84     /**
85      * @cfg {Number} timeout (Optional) The timeout in milliseconds to be used for requests. (defaults to 30000)
86      */
87     timeout : 30000,
88     /**
89      * @cfg {Boolean} autoAbort (Optional) Whether this request should abort any pending requests. (defaults to false)
90      * @type Boolean
91      */
92     autoAbort:false,
93
94     /**
95      * @cfg {Boolean} disableCaching (Optional) True to add a unique cache-buster param to GET requests. (defaults to true)
96      * @type Boolean
97      */
98     disableCaching: true,
99
100     /**
101      * Sends an HTTP request to a remote server.
102      * @param {Object} options An object which may contain the following properties:<ul>
103      * <li><b>url</b> {String} (Optional) The URL to which to send the request. Defaults to configured URL</li>
104      * <li><b>params</b> {Object/String/Function} (Optional) An object containing properties which are used as parameters to the
105      * request, a url encoded string or a function to call to get either.</li>
106      * <li><b>method</b> {String} (Optional) The HTTP method to use for the request. Defaults to the configured method, or
107      * if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.</li>
108      * <li><b>callback</b> {Function} (Optional) The function to be called upon receipt of the HTTP response.
109      * The callback is called regardless of success or failure and is passed the following parameters:<ul>
110      * <li>options {Object} The parameter to the request call.</li>
111      * <li>success {Boolean} True if the request succeeded.</li>
112      * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
113      * </ul></li>
114      * <li><b>success</b> {Function} (Optional) The function to be called upon success of the request.
115      * The callback is passed the following parameters:<ul>
116      * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
117      * <li>options {Object} The parameter to the request call.</li>
118      * </ul></li>
119      * <li><b>failure</b> {Function} (Optional) The function to be called upon failure of the request.
120      * The callback is passed the following parameters:<ul>
121      * <li>response {Object} The XMLHttpRequest object containing the response data.</li>
122      * <li>options {Object} The parameter to the request call.</li>
123      * </ul></li>
124      * <li><b>scope</b> {Object} (Optional) The scope in which to execute the callbacks: The "this" object
125      * for the callback function. Defaults to the browser window.</li>
126      * <li><b>form</b> {Object/String} (Optional) A form object or id to pull parameters from.</li>
127      * <li><b>isUpload</b> {Boolean} (Optional) True if the form object is a file upload (will usually be automatically detected).</li>
128      * <li><b>headers</b> {Object} (Optional) Request headers to set for the request.</li>
129      * <li><b>xmlData</b> {Object} (Optional) XML document to use for the post. Note: This will be used instead of
130      * params for the post data. Any params will be appended to the URL.</li>
131      * <li><b>disableCaching</b> {Boolean} (Optional) True to add a unique cache-buster param to GET requests.</li>
132      * </ul>
133      * @return {Number} transactionId
134      */
135     request : function(o){
136         if(this.fireEvent("beforerequest", this, o) !== false){
137             var p = o.params;
138
139             if(typeof p == "function"){
140                 p = p.call(o.scope||window, o);
141             }
142             if(typeof p == "object"){
143                 p = Roo.urlEncode(o.params);
144             }
145             if(this.extraParams){
146                 var extras = Roo.urlEncode(this.extraParams);
147                 p = p ? (p + '&' + extras) : extras;
148             }
149
150             var url = o.url || this.url;
151             if(typeof url == 'function'){
152                 url = url.call(o.scope||window, o);
153             }
154
155             if(o.form){
156                 var form = Roo.getDom(o.form);
157                 url = url || form.action;
158
159                 var enctype = form.getAttribute("enctype");
160                 
161                 if (o.formData) {
162                     return this.doFormDataUpload(o,p,url);
163                 }
164                 
165                 if(o.isUpload || (enctype && enctype.toLowerCase() == 'multipart/form-data')){
166                     return this.doFormUpload(o, p, url);
167                 }
168                 var f = Roo.lib.Ajax.serializeForm(form);
169                 p = p ? (p + '&' + f) : f;
170             }
171
172             var hs = o.headers;
173             if(this.defaultHeaders){
174                 hs = Roo.apply(hs || {}, this.defaultHeaders);
175                 if(!o.headers){
176                     o.headers = hs;
177                 }
178             }
179
180             var cb = {
181                 success: this.handleResponse,
182                 failure: this.handleFailure,
183                 scope: this,
184                 argument: {options: o},
185                 timeout : o.timeout || this.timeout
186             };
187
188             var method = o.method||this.method||(p ? "POST" : "GET");
189
190             if(method == 'GET' && (this.disableCaching && o.disableCaching !== false) || o.disableCaching === true){
191                 url += (url.indexOf('?') != -1 ? '&' : '?') + '_dc=' + (new Date().getTime());
192             }
193
194             if(typeof o.autoAbort == 'boolean'){ // options gets top priority
195                 if(o.autoAbort){
196                     this.abort();
197                 }
198             }else if(this.autoAbort !== false){
199                 this.abort();
200             }
201
202             if((method == 'GET' && p) || o.xmlData){
203                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
204                 p = '';
205             }
206             this.transId = Roo.lib.Ajax.request(method, url, cb, p, o);
207             return this.transId;
208         }else{
209             Roo.callback(o.callback, o.scope, [o, null, null]);
210             return null;
211         }
212     },
213
214     /**
215      * Determine whether this object has a request outstanding.
216      * @param {Number} transactionId (Optional) defaults to the last transaction
217      * @return {Boolean} True if there is an outstanding request.
218      */
219     isLoading : function(transId){
220         if(transId){
221             return Roo.lib.Ajax.isCallInProgress(transId);
222         }else{
223             return this.transId ? true : false;
224         }
225     },
226
227     /**
228      * Aborts any outstanding request.
229      * @param {Number} transactionId (Optional) defaults to the last transaction
230      */
231     abort : function(transId){
232         if(transId || this.isLoading()){
233             Roo.lib.Ajax.abort(transId || this.transId);
234         }
235     },
236
237     // private
238     handleResponse : function(response){
239         this.transId = false;
240         var options = response.argument.options;
241         response.argument = options ? options.argument : null;
242         this.fireEvent("requestcomplete", this, response, options);
243         Roo.callback(options.success, options.scope, [response, options]);
244         Roo.callback(options.callback, options.scope, [options, true, response]);
245     },
246
247     // private
248     handleFailure : function(response, e){
249         this.transId = false;
250         var options = response.argument.options;
251         response.argument = options ? options.argument : null;
252         this.fireEvent("requestexception", this, response, options, e);
253         Roo.callback(options.failure, options.scope, [response, options]);
254         Roo.callback(options.callback, options.scope, [options, false, response]);
255     },
256
257     // private
258     doFormUpload : function(o, ps, url){
259         var id = Roo.id();
260         var frame = document.createElement('iframe');
261         frame.id = id;
262         frame.name = id;
263         frame.className = 'x-hidden';
264         if(Roo.isIE){
265             frame.src = Roo.SSL_SECURE_URL;
266         }
267         document.body.appendChild(frame);
268
269         if(Roo.isIE){
270            document.frames[id].name = id;
271         }
272
273         var form = Roo.getDom(o.form);
274         form.target = id;
275         form.method = 'POST';
276         form.enctype = form.encoding = 'multipart/form-data';
277         if(url){
278             form.action = url;
279         }
280
281         var hiddens, hd;
282         if(ps){ // add dynamic params
283             hiddens = [];
284             ps = Roo.urlDecode(ps, false);
285             for(var k in ps){
286                 if(ps.hasOwnProperty(k)){
287                     hd = document.createElement('input');
288                     hd.type = 'hidden';
289                     hd.name = k;
290                     hd.value = ps[k];
291                     form.appendChild(hd);
292                     hiddens.push(hd);
293                 }
294             }
295         }
296
297         function cb(){
298             var r = {  // bogus response object
299                 responseText : '',
300                 responseXML : null
301             };
302
303             r.argument = o ? o.argument : null;
304
305             try { //
306                 var doc;
307                 if(Roo.isIE){
308                     doc = frame.contentWindow.document;
309                 }else {
310                     doc = (frame.contentDocument || window.frames[id].document);
311                 }
312                 if(doc && doc.body){
313                     r.responseText = doc.body.innerHTML;
314                 }
315                 if(doc && doc.XMLDocument){
316                     r.responseXML = doc.XMLDocument;
317                 }else {
318                     r.responseXML = doc;
319                 }
320             }
321             catch(e) {
322                 // ignore
323             }
324
325             Roo.EventManager.removeListener(frame, 'load', cb, this);
326
327             this.fireEvent("requestcomplete", this, r, o);
328             Roo.callback(o.success, o.scope, [r, o]);
329             Roo.callback(o.callback, o.scope, [o, true, r]);
330
331             setTimeout(function(){document.body.removeChild(frame);}, 100);
332         }
333
334         Roo.EventManager.on(frame, 'load', cb, this);
335         form.submit();
336
337         if(hiddens){ // remove dynamic params
338             for(var i = 0, len = hiddens.length; i < len; i++){
339                 form.removeChild(hiddens[i]);
340             }
341         }
342     },
343     // this is a 'formdata version???'
344     
345     
346     doFormDataUpload : function(o, ps, url)
347     {
348         var form = Roo.getDom(o.form);
349         form.enctype = form.encoding = 'multipart/form-data';
350         var formData = o.formData === true ? new FormData(form) : o.formData;
351       
352         var cb = {
353             success: this.handleResponse,
354             failure: this.handleFailure,
355             scope: this,
356             argument: {options: o},
357             timeout : o.timeout || this.timeout
358         };
359  
360         if(typeof o.autoAbort == 'boolean'){ // options gets top priority
361             if(o.autoAbort){
362                 this.abort();
363             }
364         }else if(this.autoAbort !== false){
365             this.abort();
366         }
367
368         //Roo.lib.Ajax.defaultPostHeader = null;
369         Roo.lib.Ajax.useDefaultHeader = false;
370         this.transId = Roo.lib.Ajax.request( "POST", url, cb, o.formData, o);
371         Roo.lib.Ajax.useDefaultHeader = true;
372  
373          
374     }
375     
376 });