.: Ajax Pages :.


In general, Ajax Pages are like regular HTML files with two exceptions:
  1. They hava a .ajp file extension
  2. They can hava JavaScript code embedded in them
The abitility to embed JavaScript code within an AJP page is what makes this tool powerful and easy to use as a client-side template scripting engine. Another major diference between Ajax Pages and other tools is that it doesn't rely on directly manipulating the Brower's DOM to make things dynamic.

There are only three diferent tags that you have to learn in order to make an AJP page.

First tag is <% (JavaScript code) %>. This tag inserts a JavaScript code into a page. Here is a Hello World example, this example will write "Hello World" five times on the screen:

<html>
<body>
<% for ( i=0; i<5; i++ ) { %>
    Hello World <br>
<% } %>
</body>
</html>


Our second tag is <%= (some JavaScript variable) %>. This tag streames out some text from the variable inside the tag. Another Hello World example using this tag:

<html>
<body>
<% var hello = "Hello World"; %>
<%=hello%>
</body>
</html>


Our third tag is <%@include file="header.ajp" context=a %>. This tag includes another AJP page into the current page. The attribute file defines the file to be included and the context attribute defines some context to be associated with that template. The context attribute is optional. A simple example using the include tag:

<html>
<body>
<%@include file="header.ajp" %>
Main page <br>
<%@include file="footer.ajp"%>
</body>
</html>
 
To process the template, you have to use the Ajax Pages JavaScript class. The code below shows how to do that.

<html>
<script language="javascript">

function init() {
    var outputArea     = document.getElementById("output");
    var ajp = new AjaxPages();
    ajp.load("example.ajp");
    var processor = ajp.getProcessor();
    outputArea.innerHTML = processor();
}

</script>
<body onload="init()">
<div id="output">
...loading
</div>

</body>
</html>

 
The last thing we can do is pass a context to the template. This way, the template doesn't depend on the JavaScript Global Scope. To do that we only pass an object to the template processor. Example below:

outputArea.innerHTML = processor({hello:"Hello World");

The context will be available to the template as the context variable. The AJP template example below shows how to access the context.

<html>
<body>
<%=context.hello%>
</body>
</html>


When you include a template, you can pass a context too.

<html>
<body>
<%@include file="example.ajp" context=mycontext %>
</body>
</html>


That's pretty much it.



SourceForge.net Logo

Copyright (c) 2005 Gustavo Ribeiro Amigo