AJAXPRC : the JavaScript Remote Procedure Call, fast and easy .
It allows JavaScript to be able to call into the server-side methods synchronously or asynchronously, based on JSON, open-source license(LGPL).

Use AJAXRPC, you can develop as a traditional C / S procedures, to develop the WEB program that allows WEB development simpler and more efficient.

Languages Supported: Java, .Net, Php.
Browsers Supported: IE、FireFox、Opera、Safari、Chrome.

Latest version: 1.0
Latest updated: 2010-10-10

AJAXRPC Quick Start

First,we have to define a class and a static method:

public class Test {
	public static String sayHello(String name){
		return "hello, " + name;
	}
}

Note: The static methord must be a public method.

Then we can call the method on the server by the AJAXRPC client program.

Note:When we call the RPC methods,if there is no callback function, then the call is synchronous;if there is one, then the call is asynchronous.

The Synchronous Call

<script type="text/javascript">
......
try{
    var obj = Test.sayHello('world!');
    ......
}catch(e){
    //e.error 
    //e.message
}
......
</script>

If there is no callback funtion,we use the "try-catch" method to handle errors.In The Synchronous Calls mode, an exception will be throwed when network errors, BLL errors(Business Logic Level Errors) ,or orther errors occurs.

The Asynchronous Call

<script type="text/javascript">
......
Test.sayHello('world!',
    function(obj){          //success callback function
        ......
    },
    function(error, message){    //fail callback function
    }

);
......
</script>

The callback funtions are used for the arguments.If there is only one callback funtion,we take it as the success callback function.

When we call the methods on the server by Javascript,some arguments will be passed which.are fit to the following stipulated typecast table.

Datatype Mapping Table

AJAXRPC supports basedatatype, customized class, but generic is not supported.

Javascript Java .Net Php 说明
Number Short,short
Integer,int
Long,long
Float,float
Double,double
short,Int16
int,Int32
long,Int64
float
Double,double
Integer
Float
Double
Digital is no strict boundaries between types, you can convert any
Boolean Boolean,boolean Boolean,bool Boolean  
String String String,string String  
Date Date DateTime String Date string is "Ymd \ TH: i: s" format, php require additional treatment
Object HashMap,Map Hashtable,IDictionary Object  
Array ArrayList,List ArrayList,IList Array  
null null null NULL  

The AJAXRPC Test Example

First,you should have a classs on the server which contains some static methods:

public class Test {
	//test Date
	public static Date getTime(){
		return new Date();
	}
	//test Number
	public static int add(int a, int b){
		return a + b;
	}
	//test String
	public static String sayHello(String name){
		return "hello, " + name;
	}
	//test Boolean
	public static Boolean isTrue(Boolean b){
		return b == true;
	}
	//test Object
	public static String addUser(Map user){
		String id = UUID.randomUUID().toString();
		user.put("id", id);
		//insert to database
		//...
		return id;
	}
	//test Array
	public static List getUsers(String name){
		List users = new ArrayList();
		for(int i=0; i<20; i++){
			Map user = new HashMap();
			user.put("name", name+i);
			user.put("gender",  i%2);
			user.put("birthday", new Date());

			users.add(user);
		}
		return users;
	}
	//test user defined class
	public static User updateUser(User user)
	{
	    user.birthday = new Date();
	    //update to database...
	    return user;
	}
	//test user defined class array
	public static User[] saveUsers(User[] users)
	{
	    for (int i = 0, l = users.length; i < l; i++)
	    {
	        User user = users[i];
	        user.name = "Server" + i;
	        user.birthday = new Date();
	        //update to database...
	    }
	    return users;
	}
}

There are four easy steps to ues AJAXRPC which are in turn Describe RPC, Release RPC, Generate Client Agent Script, Create JavaScript RPC Client Object and Call methods on the server.

1.rpc_config.xml

This xml file is used for describing RPC

<?xml version="1.0″ encoding="UTF-8″?>
<services>
	<service id="Test" class="Test"/>
</services>

Explains:
1.The value of the "class" attribute is the ClassName on the server;the value of the “id" attribute is the ClassName in the JavaScript code, and you can have an custom value of the "id" attribute.
2.All the publc static methods in the defined class, will be published to the client.
3.In the Php language, the element “service" have to contain a atrribute which takes the value of one file path.For example:<service id="Test" class="Test" path="/test/Test.php"/>
4.In the Java language, the file rpc_config.xml have to be put in the web.xml directory.

2.ajaxrpc/Service.jsp

The method to release RPC server-side follows the under example “ajaxrpc/Service.jsp".

<%@ page import="org.ajaxrpc.*" %> 
<%      HttpContext.setCurrent(request, response);

      AJAXRPC_Server server = new AJAXRPC_Server("rpc_config.xml");
      server.run();
%>

3.ajaxrpc/Script.jsp

The method to generate client agent script automatically follows the under example “ajaxrpc/Script.jsp".

<%@ page import="org.ajaxrpc.*" %>  <%
      HttpContext.setCurrent(request, response);

      AJAXRPC_Script script = new AJAXRPC_Script("rpc_config.xml");
      response.getWriter().write(script.getScripts());
%>

4.Call methods on the server by JavaScript

There are following things for you::

1)Import the script file AJAXRPC.js;
2)Generate client agent script ajaxrpc/Script.jsp;
3)Create JavaScript RPC Client Object new AJAXRPC_Client("ajaxrpc/Server.jsp");
4)Call methods on the server directly.

<html>
<head>
    <title>Test AJAXRPC</title>
</head>

<body>
    <input type="button" value="test Date" onclick="testDate()" /><br />
    <input type="button" value="test Number" onclick="testNumber()" /><br />
    <input type="button" value="test String" onclick="testString()" /><br />
    <input type="button" value="test Boolean" onclick="testBoolean()" /><br />

    <input type="button" value="test Object" onclick="testObject()" /><br />
    <input type="button" value="test Array" onclick="testArray()" /><br />
    <input type="button" value="test User Class" onclick="testUserClass()" /><br />   
    <input type="button" value="test UserClass Array" onclick="testUserClassArray()" /><br />  
</body>

</html>
<script src="scripts/AJAXRPC.js" type="text/javascript"></script>
<script src="ajaxrpc/Script.jsp" type="text/javascript"></script>
<script type="text/javascript">
var client = new AJAXRPC_Client('ajaxrpc/Server.jsp');
var Test = client.Test;

function testDate(){
    var o = Test.getTime();
    alert(o);
}
function testNumber(){
    var o = Test.add(1, 10);
    alert(o);
}
function testString(){
    var o = Test.sayHello('world!');
    alert(o);
}
function testBoolean(){
    var o = Test.isTrue(true);
    alert(o);
    var o = Test.isTrue(false);
    alert(o);
}
function testObject(){
    var user = {
        id: null,
        name: 'ajaxrpc',
        birthday: new Date(),
        gender: 1
    };
    var id = Test.addUser(user);
    alert(id);
}
function testArray(){
    var users = Test.getUsers('ajaxrpc');
    alert(users.length +":"+ users[0].name +":"+ users[users.length-1].name);
}
function testUserClass(){
    var user = {
        id: null,
        name: 'ajaxrpc',
        birthday: null,
        gender: 1
    };
    user = Test.updateUser(user);
    alert(user.birthday);
}
function testUserClassArray(){
    var users = [];
    for(var i=0; i<20; i++){
        var user = {
            id: i,
            name: 'ajaxrpc'+i,
            birthday: new Date(),
            gender: i%2
        };
        users.push(user);
    }
    var users = Test.saveUsers(users);
    alert(users.length +":"+ users[0].name +":"+ users[users.length-1].name);
}
</script>

Hope that AJAXRPC is useful to you, if you have any question, please contact us:
fcrong@gmail.com

English Version By ZhangChaoming