Friday, June 02, 2006

E4X with Server Side Javascript

I've updated the Server Side Javascript distribution to include an example which uses E4X.

E4X is described in Ecma-357 and adds a Native XML syntax to Javascript. The XML is converted to a Javascript object which can be used to query and manipulate the XML.

The E4X example servlet generates the XHTML to be displayed using:
var result = 
<html>
<head><title>HTML Using E4X!</title></head>
<body>
<p>Hello from E4X on: {new Date()}.</p>
</body>
</html>;

It embeds the current date and time by calling out to Javascript's Date object. This is done by wrapping the Javascript expression inside curly bracket: {new Date()}.

Given the XML object now stored in the 'result' variable it can be sent over the wire in the same manner as the other servlet examples:
    var text = doctype + result.toString();
resp.setContentType("text/html")
resp.setContentLength(text.length)
resp.getOutputStream().print(text)
resp.flushBuffer()

I prepend an XHTML doctype to the output as the XML generated is actually XML not HTML. This means things like <br> need to be <br/>, etc. I've not found a way to get E4X to generate HTML which is a pity - if anyone knows if it is possible I'd appreciate you dropping a comment here.

The updated code is available as javascript-server-0.2.tar.gz and in the darcs repository:

darcs get http://www.bluishcoder.co.nz/repos/javascript-server

Categories:

2 Comments:

Anonymous Fede said...

I've downloaded your javascript-server: very interesting! I'm doing some test, integrating velocity and other template engines, some confs e start script in bash. I'll back your code soon.
Later i'll integrate a java server pages parser in javascript: this make the interaction with javascript template and xml db (via e4x) very powerfull and easy.
Grat idea!

12:39 PM  
Blogger Chris Double said...

Nice! Let me know how you get on.

1:16 PM  

Post a Comment

<< Home