1 <!DOCTYPE html><html><head><title>Sencha Documentation Project</title><link rel="stylesheet" href="../reset.css" type="text/css"><link rel="stylesheet" href="../prettify.css" type="text/css"><link rel="stylesheet" href="../prettify_sa.css" type="text/css"><script type="text/javascript" src="../prettify.js"></script></head><body onload="prettyPrint()"><pre class="prettyprint"><pre><span id='Ext-data.proxy.JsonP'>/**
2 </span> * @author Ed Spencer
3 * @class Ext.data.proxy.JsonP
4 * @extends Ext.data.proxy.Server
6 * <p>JsonPProxy is useful when you need to load data from a domain other than the one your application is running
7 * on. If your application is running on http://domainA.com it cannot use {@link Ext.data.proxy.Ajax Ajax} to load its
8 * data from http://domainB.com because cross-domain ajax requests are prohibited by the browser.</p>
10 * <p>We can get around this using a JsonPProxy. JsonPProxy injects a &lt;script&gt; tag into the DOM whenever
11 * an AJAX request would usually be made. Let's say we want to load data from http://domainB.com/users - the script tag
12 * that would be injected might look like this:</p>
14 <pre><code>
15 &lt;script src="http://domainB.com/users?callback=someCallback"&gt;&lt;/script&gt;
16 </code></pre>
18 * <p>When we inject the tag above, the browser makes a request to that url and includes the response as if it was any
19 * other type of JavaScript include. By passing a callback in the url above, we're telling domainB's server that we
20 * want to be notified when the result comes in and that it should call our callback function with the data it sends
21 * back. So long as the server formats the response to look like this, everything will work:</p>
23 <pre><code>
28 name: "Ed Spencer",
29 email: "ed@sencha.com"
33 </code></pre>
35 * <p>As soon as the script finishes loading, the 'someCallback' function that we passed in the url is called with the
36 * JSON object that the server returned.</p>
38 * <p>JsonPProxy takes care of all of this automatically. It formats the url you pass, adding the callback
39 * parameter automatically. It even creates a temporary callback function, waits for it to be called and then puts
40 * the data into the Proxy making it look just like you loaded it through a normal {@link Ext.data.proxy.Ajax AjaxProxy}.
41 * Here's how we might set that up:</p>
43 <pre><code>
45 extend: 'Ext.data.Model',
46 fields: ['id', 'name', 'email']
49 var store = new Ext.data.Store({
53 url : 'http://domainB.com/users'
58 </code></pre>
60 * <p>That's all we need to do - JsonPProxy takes care of the rest. In this case the Proxy will have injected a
61 * script tag like this:
63 <pre><code>
64 &lt;script src="http://domainB.com/users?callback=stcCallback001" id="stcScript001"&gt;&lt;/script&gt;
65 </code></pre>
67 * <p><u>Customization</u></p>
69 * <p>Most parts of this script tag can be customized using the {@link #callbackParam}, {@link #callbackPrefix} and
70 * {@link #scriptIdPrefix} configurations. For example:
72 <pre><code>
73 var store = new Ext.data.Store({
77 url : 'http://domainB.com/users',
78 callbackParam: 'theCallbackFunction',
79 callbackPrefix: 'ABC',
80 scriptIdPrefix: 'injectedScript'
85 </code></pre>
87 * <p>Would inject a script tag like this:</p>
89 <pre><code>
90 &lt;script src="http://domainB.com/users?theCallbackFunction=ABC001" id="injectedScript001"&gt;&lt;/script&gt;
91 </code></pre>
93 * <p><u>Implementing on the server side</u></p>
95 * <p>The remote server side needs to be configured to return data in this format. Here are suggestions for how you
96 * might achieve this using Java, PHP and ASP.net:</p>
98 * <p>Java:</p>
100 <pre><code>
101 boolean jsonP = false;
102 String cb = request.getParameter("callback");
105 response.setContentType("text/javascript");
107 response.setContentType("application/x-json");
109 Writer out = response.getWriter();
111 out.write(cb + "(");
113 out.print(dataBlock.toJsonString());
115 out.write(");");
117 </code></pre>
119 * <p>PHP:</p>
121 <pre><code>
122 $callback = $_REQUEST['callback'];
124 // Create the output object.
125 $output = array('a' => 'Apple', 'b' => 'Banana');
129 header('Content-Type: text/javascript');
130 echo $callback . '(' . json_encode($output) . ');';
132 header('Content-Type: application/x-json');
133 echo json_encode($output);
135 </code></pre>
137 * <p>ASP.net:</p>
139 <pre><code>
140 String jsonString = "{success: true}";
141 String cb = Request.Params.Get("callback");
142 String responseString = "";
143 if (!String.IsNullOrEmpty(cb)) {
144 responseString = cb + "(" + jsonString + ")";
146 responseString = jsonString;
148 Response.Write(responseString);
149 </code></pre>
152 Ext.define('Ext.data.proxy.JsonP', {
153 extend: 'Ext.data.proxy.Server',
154 alternateClassName: 'Ext.data.ScriptTagProxy',
155 alias: ['proxy.jsonp', 'proxy.scripttag'],
156 requires: ['Ext.data.JsonP'],
158 defaultWriterType: 'base',
160 <span id='Ext-data.proxy.JsonP-cfg-callbackKey'> /**
161 </span> * @cfg {String} callbackKey (Optional) See {@link Ext.data.JsonP#callbackKey}.
163 callbackKey : 'callback',
165 <span id='Ext-data.proxy.JsonP-cfg-recordParam'> /**
166 </span> * @cfg {String} recordParam
167 * The param name to use when passing records to the server (e.g. 'records=someEncodedRecordString').
168 * Defaults to 'records'
170 recordParam: 'records',
172 <span id='Ext-data.proxy.JsonP-cfg-autoAppendParams'> /**
173 </span> * @cfg {Boolean} autoAppendParams True to automatically append the request's params to the generated url. Defaults to true
175 autoAppendParams: true,
177 constructor: function(){
179 <span id='Ext-data.proxy.JsonP-event-exception'> /**
180 </span> * @event exception
181 * Fires when the server returns an exception
182 * @param {Ext.data.proxy.Proxy} this
183 * @param {Ext.data.Request} request The request that was sent
184 * @param {Ext.data.Operation} operation The operation that triggered the request
188 this.callParent(arguments);
191 <span id='Ext-data.proxy.JsonP-method-doRequest'> /**
193 * Performs the read request to the remote domain. JsonPProxy does not actually create an Ajax request,
194 * instead we write out a <script> tag based on the configuration of the internal Ext.data.Request object
195 * @param {Ext.data.Operation} operation The {@link Ext.data.Operation Operation} object to execute
196 * @param {Function} callback A callback function to execute when the Operation has been completed
197 * @param {Object} scope The scope to execute the callback in
199 doRequest: function(operation, callback, scope) {
200 //generate the unique IDs for this request
202 writer = me.getWriter(),
203 request = me.buildRequest(operation),
204 params = request.params;
206 if (operation.allowWrite()) {
207 request = writer.write(request);
210 //apply JsonPProxy-specific attributes to the Request
212 callbackKey: me.callbackKey,
215 disableCaching: false, // handled by the proxy
216 callback: me.createRequestCallback(request, operation, callback, scope)
219 // prevent doubling up
220 if (me.autoAppendParams) {
224 request.jsonp = Ext.data.JsonP.request(request);
225 // restore on the request
226 request.params = params;
227 operation.setStarted();
228 me.lastRequest = request;
233 <span id='Ext-data.proxy.JsonP-method-createRequestCallback'> /**
235 * Creates and returns the function that is called when the request has completed. The returned function
236 * should accept a Response object, which contains the response to be read by the configured Reader.
237 * The third argument is the callback that should be called after the request has been completed and the Reader has decoded
238 * the response. This callback will typically be the callback passed by a store, e.g. in proxy.read(operation, theCallback, scope)
239 * theCallback refers to the callback argument received by this function.
240 * See {@link #doRequest} for details.
241 * @param {Ext.data.Request} request The Request object
242 * @param {Ext.data.Operation} operation The Operation being executed
243 * @param {Function} callback The callback function to be called when the request completes. This is usually the callback
244 * passed to doRequest
245 * @param {Object} scope The scope in which to execute the callback function
246 * @return {Function} The callback function
248 createRequestCallback: function(request, operation, callback, scope) {
251 return function(success, response, errorType) {
252 delete me.lastRequest;
253 me.processResponse(success, operation, request, response, callback, scope);
258 setException: function(operation, response) {
259 operation.setException(operation.request.jsonp.errorType);
263 <span id='Ext-data.proxy.JsonP-method-buildUrl'> /**
264 </span> * Generates a url based on a given Ext.data.Request object. Adds the params and callback function name to the url
265 * @param {Ext.data.Request} request The request object
266 * @return {String} The url
268 buildUrl: function(request) {
270 url = me.callParent(arguments),
271 params = Ext.apply({}, request.params),
272 filters = params.filters,
276 delete params.filters;
278 if (me.autoAppendParams) {
279 url = Ext.urlAppend(url, Ext.Object.toQueryString(params));
282 if (filters && filters.length) {
283 for (i = 0; i < filters.length; i++) {
287 url = Ext.urlAppend(url, filter.property + "=" + filter.value);
292 //if there are any records present, append them to the url also
293 records = request.records;
295 if (Ext.isArray(records) && records.length > 0) {
296 url = Ext.urlAppend(url, Ext.String.format("{0}={1}", me.recordParam, me.encodeRecords(records)));
303 destroy: function() {
308 <span id='Ext-data.proxy.JsonP-method-abort'> /**
309 </span> * Aborts the current server request if one is currently running
312 var lastRequest = this.lastRequest;
314 Ext.data.JsonP.abort(lastRequest.jsonp);
318 <span id='Ext-data.proxy.JsonP-method-encodeRecords'> /**
319 </span> * Encodes an array of records into a string suitable to be appended to the script src url. This is broken
320 * out into its own function so that it can be easily overridden.
321 * @param {Array} records The records array
322 * @return {String} The encoded records string
324 encodeRecords: function(records) {
325 var encoded = "",
327 len = records.length;
329 for (; i < len; i++) {
330 encoded += Ext.Object.toQueryString(records[i].data);
336 </pre></pre></body></html>