How to ExtJS 4 JsonP


The JsonP proxy (Ext.data.proxy.JsonP) is provided to handle cross domain queries and posts. Using it is straight forward but just swapping out an ajax or json proxy and using a jsonp proxy is not enough.

Here’s an example proxy definition for a TreeStore using jsonp:

1
2
3
4
proxy: {
    type: 'jsonp',
    url: 'http://mogg2008/photos/get-folders.php'
}
proxy: {
	type: 'jsonp',
	url: 'http://mogg2008/photos/get-folders.php'
}

But dropping this in place of an ajax or json proxy is guaranteed to fail unless the server is ready to support an ExtJS jsonp proxy. When using a regular proxy the response is handled by ExtJS directly when the ajax request returns. But when going cross domain this doesn’t work (try it!). Instead the request and response are handled differently. Importantly, the response MUST be a javascript snippet to execute a named callback. The callback takes one parameter: the json that would ordinarily be returned.

So what’s the name of the callback to execute? The callback name is given by the ‘callback’ name of the jsonp query string. Here’s what the request might resemble:

  http://someotherdomain.com?callback=Ext.json.callback

Here’s some PHP code to grab and use the callback name:

1
2
3
4
5
6
7
8
9
$callback = "";
if (isset($_REQUEST['callback']))
  $callback = $_REQUEST['callback'];
 
$nodes = ... Generate response array ...
 
echo ($callback=="" ? "" : "$callback(")
  . json_encode($nodes)
  . ($callback=="" ? "" : ");");
$callback = "";
if (isset($_REQUEST['callback']))
  $callback = $_REQUEST['callback'];

$nodes = ... Generate response array ...

echo ($callback=="" ? "" : "$callback(")
  . json_encode($nodes)
  . ($callback=="" ? "" : ");");

If the callback name is ‘Ext.json.callback’ then the last line will generate a response like:

Ext.json.callback(… json here …);

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!