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