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