AJAX – Getting Started ExtJs with Perl CGI

I usually use ExtJs with Struts, PHP, or Google Web Toolkit (GWT). Here i will create a simple tree panel sample using ExtJS and Perl CGI.

Here is our directory structure:
extjstest
-extjs (directory)
-JSON (directory)
-data.cgi (file)
-index.html (file)
-JSON.pm (file)

requirements:
1. Download the latest Ext Js from here and extract the archive files to extjs folder
2. You have mod Perl cgi enabled with your apache server, you can see my post at Perl for how to set up mod mod Perl CGI in apache
3. JSON module for Perl, you can download it from here

Enough talk, let’s start coding!

Filename: index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"
	href="extjs/resources/css/ext-all.css" />
<script type="text/javascript" src="extjs/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="extjs/ext-all-debug.js"></script>
<script type="text/javascript">
	Ext.onReady(function() {
		var Tree = Ext.tree;
		var tree = new Tree.TreePanel( {
			el : 'tree-div',
			autoScroll : true,
			border: false,
			title: 'My First Panel',
			animate : true,
			enableDD : true,
			containerScroll : true,
			loader : new Tree.TreeLoader( {
				<strong>dataUrl : 'data.cgi'</strong>
			})
		});
		// set the root node
			var root = new Tree.AsyncTreeNode( {
				text : 'Ext JS',
				draggable : false,
				id : 'source'
			});
			tree.setRootNode(root);

			 // render the tree
		    tree.render();
		    root.expand();
		});
</script>

</head>
<body>
<div id="tree-div" style="overflow:auto; height:300px;width:250px;border:1px solid #c3daf9;"></div>
</body>
</html></a>

As you see above code, the treepanel gets the data url from data.cgi. What is this data.cgi produce? the data.cgi will response JSON type to the html, JSON is optimized version of XML.

2. data.cgi

#!/usr/bin/perl -w
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use Storable;
use JSON;
$page = new CGI;


print "Content-type: application/json\n\n";
@mydata0={'text'=>'merci','id'=>'3','leaf'=>true,'cls'=>'file'};
@mydata1={'text'=>'audi','id'=>'2','children'=>\@mydata0};
@mydata2={'text'=>'benz','id'=>'1','children'=>\@mydata1};

@mydata=(@mydata2,@mydata3);

$text = objToJson(\@mydata);

print $text;
exit (0);

Open your browser and point to http://localhost/extjstest/index.html. If everything fine, you should see a treepanel displayed.

Advertisements