[Catalyst] [Task] Building a better JavaScript (AJAX) toolkit

Don Arbow donarb at nwlink.com
Wed Dec 21 01:34:35 CET 2005


On Dec 20, 2005, at 2:44 PM, Brandon Black wrote:

> How did they get around not using XmlHttpRequest? Load json objects
> via dynamic <script src="json_url"> tags or something?

Yep, pretty much. This is what the setup code looks like:

     var remoteScript = document.createElement('script');
     remoteScript.setAttribute('type', 'text/javascript');
     remoteScript.setAttribute('src',  url);
     var hd = document.getElementsByTagName('head')[0];
     hd.appendChild(remoteScript);

Once the script element is appended to the document, it loads the src 
url. One of the parameters in the url is the name of a "callback" 
function that will handle the returned data. You can treat the returned 
data as a serialized Javascript object. The JSON.pm module can 
parse/create this serialization to/from Perl hashes or arrays.

Here's an simple CGI that echoes any data passed to it as a JSON 
request (notice how it sets up the callback to be executed when it 
returns to the browser):

use CGI;
my $q = new CGI;
my $hdr = "Content-type:text/javascript\n\n";
my $callback = $q->param('callback');
print $hdr.$callback.'({content: \''.$q->param( 'json' ).'\'});';

More info on JSON at:

http://www.json.org

Don




More information about the Catalyst mailing list