commit extjs-2.2.1
[extjs.git] / source / data / ScriptTagProxy.js
1 /*\r
2  * Ext JS Library 2.2.1\r
3  * Copyright(c) 2006-2009, Ext JS, LLC.\r
4  * licensing@extjs.com\r
5  * \r
6  * http://extjs.com/license\r
7  */\r
8 \r
9 /**\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  *\r
45  * @constructor\r
46  * @param {Object} config A configuration object.\r
47  */\r
48 Ext.data.ScriptTagProxy = function(config){\r
49     Ext.data.ScriptTagProxy.superclass.constructor.call(this);\r
50     Ext.apply(this, config);\r
51     this.head = document.getElementsByTagName("head")[0];\r
52     \r
53     /**\r
54      * @event loadexception\r
55      * Fires if an exception occurs in the Proxy during data loading.  This event can be fired for one of two reasons:\r
56      * <ul><li><b>The load call timed out.</b>  This means the load callback did not execute within the time limit\r
57      * specified by {@link #timeout}.  In this case, this event will be raised and the\r
58      * fourth parameter (read error) will be null.</li>\r
59      * <li><b>The load succeeded but the reader could not read the response.</b>  This means the server returned\r
60      * data, but the configured Reader threw an error while reading the data.  In this case, this event will be \r
61      * raised and the caught error will be passed along as the fourth parameter of this event.</li></ul>\r
62      * Note that this event is also relayed through {@link Ext.data.Store}, so you can listen for it directly\r
63      * on any Store instance.\r
64      * @param {Object} this\r
65      * @param {Object} options The loading options that were specified (see {@link #load} for details).  If the load\r
66      * call timed out, this parameter will be null.\r
67      * @param {Object} arg The callback's arg object passed to the {@link #load} function\r
68      * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data.\r
69      * If the load call returned success: false, this parameter will be null.\r
70      */\r
71 };\r
72 \r
73 Ext.data.ScriptTagProxy.TRANS_ID = 1000;\r
74 \r
75 Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, {\r
76     /**\r
77      * @cfg {String} url The URL from which to request the data object.\r
78      */\r
79     /**\r
80      * @cfg {Number} timeout (optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.\r
81      */\r
82     timeout : 30000,\r
83     /**\r
84      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells\r
85      * the server the name of the callback function set up by the load call to process the returned data object.\r
86      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate\r
87      * javascript output which calls this named function passing the data object as its only parameter.\r
88      */\r
89     callbackParam : "callback",\r
90     /**\r
91      *  @cfg {Boolean} nocache (optional) Defaults to true. Disable caching by adding a unique parameter\r
92      * name to the request.\r
93      */\r
94     nocache : true,\r
95 \r
96     /**\r
97      * Load data from the configured URL, read the data object into\r
98      * a block of Ext.data.Records using the passed Ext.data.DataReader implementation, and\r
99      * process that block using the passed callback.\r
100      * @param {Object} params An object containing properties which are to be used as HTTP parameters\r
101      * for the request to the remote server.\r
102      * @param {Ext.data.DataReader} reader The Reader object which converts the data\r
103      * object into a block of Ext.data.Records.\r
104      * @param {Function} callback The function into which to pass the block of Ext.data.Records.\r
105      * The function must be passed <ul>\r
106      * <li>The Record block object</li>\r
107      * <li>The "arg" argument from the load function</li>\r
108      * <li>A boolean success indicator</li>\r
109      * </ul>\r
110      * @param {Object} scope The scope in which to call the callback\r
111      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.\r
112      */\r
113     load : function(params, reader, callback, scope, arg){\r
114         if(this.fireEvent("beforeload", this, params) !== false){\r
115 \r
116             var p = Ext.urlEncode(Ext.apply(params, this.extraParams));\r
117 \r
118             var url = this.url;\r
119             url += (url.indexOf("?") != -1 ? "&" : "?") + p;\r
120             if(this.nocache){\r
121                 url += "&_dc=" + (new Date().getTime());\r
122             }\r
123             var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;\r
124             var trans = {\r
125                 id : transId,\r
126                 cb : "stcCallback"+transId,\r
127                 scriptId : "stcScript"+transId,\r
128                 params : params,\r
129                 arg : arg,\r
130                 url : url,\r
131                 callback : callback,\r
132                 scope : scope,\r
133                 reader : reader\r
134             };\r
135             var conn = this;\r
136 \r
137             window[trans.cb] = function(o){\r
138                 conn.handleResponse(o, trans);\r
139             };\r
140 \r
141             url += String.format("&{0}={1}", this.callbackParam, trans.cb);\r
142 \r
143             if(this.autoAbort !== false){\r
144                 this.abort();\r
145             }\r
146 \r
147             trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);\r
148 \r
149             var script = document.createElement("script");\r
150             script.setAttribute("src", url);\r
151             script.setAttribute("type", "text/javascript");\r
152             script.setAttribute("id", trans.scriptId);\r
153             this.head.appendChild(script);\r
154 \r
155             this.trans = trans;\r
156         }else{\r
157             callback.call(scope||this, null, arg, false);\r
158         }\r
159     },\r
160 \r
161     // private\r
162     isLoading : function(){\r
163         return this.trans ? true : false;\r
164     },\r
165 \r
166     /**\r
167      * Abort the current server request.\r
168      */\r
169     abort : function(){\r
170         if(this.isLoading()){\r
171             this.destroyTrans(this.trans);\r
172         }\r
173     },\r
174 \r
175     // private\r
176     destroyTrans : function(trans, isLoaded){\r
177         this.head.removeChild(document.getElementById(trans.scriptId));\r
178         clearTimeout(trans.timeoutId);\r
179         if(isLoaded){\r
180             window[trans.cb] = undefined;\r
181             try{\r
182                 delete window[trans.cb];\r
183             }catch(e){}\r
184         }else{\r
185             // if hasn't been loaded, wait for load to remove it to prevent script error\r
186             window[trans.cb] = function(){\r
187                 window[trans.cb] = undefined;\r
188                 try{\r
189                     delete window[trans.cb];\r
190                 }catch(e){}\r
191             };\r
192         }\r
193     },\r
194 \r
195     // private\r
196     handleResponse : function(o, trans){\r
197         this.trans = false;\r
198         this.destroyTrans(trans, true);\r
199         var result;\r
200         try {\r
201             result = trans.reader.readRecords(o);\r
202         }catch(e){\r
203             this.fireEvent("loadexception", this, o, trans.arg, e);\r
204             trans.callback.call(trans.scope||window, null, trans.arg, false);\r
205             return;\r
206         }\r
207         this.fireEvent("load", this, o, trans.arg);\r
208         trans.callback.call(trans.scope||window, result, trans.arg, true);\r
209     },\r
210 \r
211     // private\r
212     handleFailure : function(trans){\r
213         this.trans = false;\r
214         this.destroyTrans(trans, false);\r
215         this.fireEvent("loadexception", this, null, trans.arg);\r
216         trans.callback.call(trans.scope||window, null, trans.arg, false);\r
217     }\r
218 });