Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / data / ScriptTagProxy.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**\r
8  * @class Ext.data.ScriptTagProxy\r
9  * @extends Ext.data.DataProxy\r
10  * An implementation of Ext.data.DataProxy that reads a data object from a URL which may be in a domain\r
11  * other than the originating domain of the running page.<br>\r
12  * <p>\r
13  * <b>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain\r
14  * of the running page, you must use this class, rather than HttpProxy.</b><br>\r
15  * <p>\r
16  * The content passed back from a server resource requested by a ScriptTagProxy <b>must</b> be executable JavaScript\r
17  * source code because it is used as the source inside a &lt;script> tag.<br>\r
18  * <p>\r
19  * In order for the browser to process the returned data, the server must wrap the data object\r
20  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.\r
21  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy\r
22  * depending on whether the callback name was passed:\r
23  * <p>\r
24  * <pre><code>\r
25 boolean scriptTag = false;\r
26 String cb = request.getParameter("callback");\r
27 if (cb != null) {\r
28     scriptTag = true;\r
29     response.setContentType("text/javascript");\r
30 } else {\r
31     response.setContentType("application/x-json");\r
32 }\r
33 Writer out = response.getWriter();\r
34 if (scriptTag) {\r
35     out.write(cb + "(");\r
36 }\r
37 out.print(dataBlock.toJsonString());\r
38 if (scriptTag) {\r
39     out.write(");");\r
40 }\r
41 </code></pre>\r
42  *\r
43  * @constructor\r
44  * @param {Object} config A configuration object.\r
45  */\r
46 Ext.data.ScriptTagProxy = function(config){\r
47     Ext.apply(this, config);\r
48 \r
49     Ext.data.ScriptTagProxy.superclass.constructor.call(this, config);\r
50 \r
51     this.head = document.getElementsByTagName("head")[0];\r
52 \r
53     /**\r
54      * @event loadexception\r
55      * <b>Deprecated</b> in favor of 'exception' event.\r
56      * Fires if an exception occurs in the Proxy during data loading.  This event can be fired for one of two reasons:\r
57      * <ul><li><b>The load call timed out.</b>  This means the load callback did not execute within the time limit\r
58      * specified by {@link #timeout}.  In this case, this event will be raised and the\r
59      * fourth parameter (read error) will be null.</li>\r
60      * <li><b>The load succeeded but the reader could not read the response.</b>  This means the server returned\r
61      * data, but the configured Reader threw an error while reading the data.  In this case, this event will be\r
62      * raised and the caught error will be passed along as the fourth parameter of this event.</li></ul>\r
63      * Note that this event is also relayed through {@link Ext.data.Store}, so you can listen for it directly\r
64      * on any Store instance.\r
65      * @param {Object} this\r
66      * @param {Object} options The loading options that were specified (see {@link #load} for details).  If the load\r
67      * call timed out, this parameter will be null.\r
68      * @param {Object} arg The callback's arg object passed to the {@link #load} function\r
69      * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data.\r
70      * If the remote request returns success: false, this parameter will be null.\r
71      */\r
72 };\r
73 \r
74 Ext.data.ScriptTagProxy.TRANS_ID = 1000;\r
75 \r
76 Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, {\r
77     /**\r
78      * @cfg {String} url The URL from which to request the data object.\r
79      */\r
80     /**\r
81      * @cfg {Number} timeout (optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.\r
82      */\r
83     timeout : 30000,\r
84     /**\r
85      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells\r
86      * the server the name of the callback function set up by the load call to process the returned data object.\r
87      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate\r
88      * javascript output which calls this named function passing the data object as its only parameter.\r
89      */\r
90     callbackParam : "callback",\r
91     /**\r
92      *  @cfg {Boolean} nocache (optional) Defaults to true. Disable caching by adding a unique parameter\r
93      * name to the request.\r
94      */\r
95     nocache : true,\r
96 \r
97     /**\r
98      * HttpProxy implementation of DataProxy#doRequest\r
99      * @param {String} action\r
100      * @param {Ext.data.Record/Ext.data.Record[]} rs If action is <tt>read</tt>, rs will be null\r
101      * @param {Object} params An object containing properties which are to be used as HTTP parameters\r
102      * for the request to the remote server.\r
103      * @param {Ext.data.DataReader} reader The Reader object which converts the data\r
104      * object into a block of Ext.data.Records.\r
105      * @param {Function} callback The function into which to pass the block of Ext.data.Records.\r
106      * The function must be passed <ul>\r
107      * <li>The Record block object</li>\r
108      * <li>The "arg" argument from the load function</li>\r
109      * <li>A boolean success indicator</li>\r
110      * </ul>\r
111      * @param {Object} scope The scope in which to call the callback\r
112      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.\r
113      */\r
114     doRequest : function(action, rs, params, reader, callback, scope, arg) {\r
115         var p = Ext.urlEncode(Ext.apply(params, this.extraParams));\r
116 \r
117         var url = this.buildUrl(action, rs);\r
118         if (!url) {\r
119             throw new Ext.data.Api.Error('invalid-url', url);\r
120         }\r
121         url = Ext.urlAppend(url, p);\r
122 \r
123         if(this.nocache){\r
124             url = Ext.urlAppend(url, '_dc=' + (new Date().getTime()));\r
125         }\r
126         var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;\r
127         var trans = {\r
128             id : transId,\r
129             action: action,\r
130             cb : "stcCallback"+transId,\r
131             scriptId : "stcScript"+transId,\r
132             params : params,\r
133             arg : arg,\r
134             url : url,\r
135             callback : callback,\r
136             scope : scope,\r
137             reader : reader\r
138         };\r
139         window[trans.cb] = this.createCallback(action, rs, trans);\r
140         url += String.format("&{0}={1}", this.callbackParam, trans.cb);\r
141         if(this.autoAbort !== false){\r
142             this.abort();\r
143         }\r
144 \r
145         trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);\r
146 \r
147         var script = document.createElement("script");\r
148         script.setAttribute("src", url);\r
149         script.setAttribute("type", "text/javascript");\r
150         script.setAttribute("id", trans.scriptId);\r
151         this.head.appendChild(script);\r
152 \r
153         this.trans = trans;\r
154     },\r
155 \r
156     // @private createCallback\r
157     createCallback : function(action, rs, trans) {\r
158         var self = this;\r
159         return function(res) {\r
160             self.trans = false;\r
161             self.destroyTrans(trans, true);\r
162             if (action === Ext.data.Api.actions.read) {\r
163                 self.onRead.call(self, action, trans, res);\r
164             } else {\r
165                 self.onWrite.call(self, action, trans, res, rs);\r
166             }\r
167         };\r
168     },\r
169     /**\r
170      * Callback for read actions\r
171      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
172      * @param {Object} trans The request transaction object\r
173      * @param {Object} res The server response\r
174      * @private\r
175      */\r
176     onRead : function(action, trans, res) {\r
177         var result;\r
178         try {\r
179             result = trans.reader.readRecords(res);\r
180         }catch(e){\r
181             // @deprecated: fire loadexception\r
182             this.fireEvent("loadexception", this, trans, res, e);\r
183 \r
184             this.fireEvent('exception', this, 'response', action, trans, res, e);\r
185             trans.callback.call(trans.scope||window, null, trans.arg, false);\r
186             return;\r
187         }\r
188         if (result.success === false) {\r
189             // @deprecated: fire old loadexception for backwards-compat.\r
190             this.fireEvent('loadexception', this, trans, res);\r
191 \r
192             this.fireEvent('exception', this, 'remote', action, trans, res, null);\r
193         } else {\r
194             this.fireEvent("load", this, res, trans.arg);\r
195         }\r
196         trans.callback.call(trans.scope||window, result, trans.arg, result.success);\r
197     },\r
198     /**\r
199      * Callback for write actions\r
200      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
201      * @param {Object} trans The request transaction object\r
202      * @param {Object} res The server response\r
203      * @private\r
204      */\r
205     onWrite : function(action, trans, response, rs) {\r
206         var reader = trans.reader;\r
207         try {\r
208             // though we already have a response object here in STP, run through readResponse to catch any meta-data exceptions.\r
209             var res = reader.readResponse(action, response);\r
210         } catch (e) {\r
211             this.fireEvent('exception', this, 'response', action, trans, res, e);\r
212             trans.callback.call(trans.scope||window, null, res, false);\r
213             return;\r
214         }\r
215         if(!res.success === true){\r
216             this.fireEvent('exception', this, 'remote', action, trans, res, rs);\r
217             trans.callback.call(trans.scope||window, null, res, false);\r
218             return;\r
219         }\r
220         this.fireEvent("write", this, action, res.data, res, rs, trans.arg );\r
221         trans.callback.call(trans.scope||window, res.data, res, true);\r
222     },\r
223 \r
224     // private\r
225     isLoading : function(){\r
226         return this.trans ? true : false;\r
227     },\r
228 \r
229     /**\r
230      * Abort the current server request.\r
231      */\r
232     abort : function(){\r
233         if(this.isLoading()){\r
234             this.destroyTrans(this.trans);\r
235         }\r
236     },\r
237 \r
238     // private\r
239     destroyTrans : function(trans, isLoaded){\r
240         this.head.removeChild(document.getElementById(trans.scriptId));\r
241         clearTimeout(trans.timeoutId);\r
242         if(isLoaded){\r
243             window[trans.cb] = undefined;\r
244             try{\r
245                 delete window[trans.cb];\r
246             }catch(e){}\r
247         }else{\r
248             // if hasn't been loaded, wait for load to remove it to prevent script error\r
249             window[trans.cb] = function(){\r
250                 window[trans.cb] = undefined;\r
251                 try{\r
252                     delete window[trans.cb];\r
253                 }catch(e){}\r
254             };\r
255         }\r
256     },\r
257 \r
258     // private\r
259     handleFailure : function(trans){\r
260         this.trans = false;\r
261         this.destroyTrans(trans, false);\r
262         if (trans.action === Ext.data.Api.actions.read) {\r
263             // @deprecated firing loadexception\r
264             this.fireEvent("loadexception", this, null, trans.arg);\r
265         }\r
266 \r
267         this.fireEvent('exception', this, 'response', trans.action, {\r
268             response: null,\r
269             options: trans.arg\r
270         });\r
271         trans.callback.call(trans.scope||window, null, trans.arg, false);\r
272     },\r
273 \r
274     // inherit docs\r
275     destroy: function(){\r
276         this.abort();\r
277         Ext.data.ScriptTagProxy.superclass.destroy.call(this);\r
278     }\r
279 });