EXAMPLE:

SERVER:

<%@ WebHandler Language="C#" CodeBehind="TestService.ashx.cs" Class="TestService" %>

    [JsonRpcObject(Namespace="Client")]
    public class TestService : JsonRpcService
    {

        [JsonRpcMethod]
        public int Sum(int a, int b)
        {
            return a + b;
        }

        [JsonRpcMethod(Name = "getMessage")]
        public string GetMessage(string name)
        {
            return "Hello " + name + "!";
        }

     }

CLIENT:

<html>
<head>

   <title>JsonRpc 2.0 - Test</title>

   <script type="text/javascript" src="ext-core.js"></script>
   <script type="text/javascript" src="JsonRpc.js"></script>
   <script type="text/javascript" src="TestService.ashx"></script>

</head>
 
<body>

<div>JsonRpc 2.0 - Test</div>
 
    <script type="text/javascript">

        var service = new Client.TestService();

        //create the callback handlers
        service.SumCompleted = function (response)
        {
            if (response.error)
            {
                alert(response.error.message)
            }
            else
            {
                alert(response.result);
            }
        }

        service.getMessageSuccess = function (result)
        {
            alert(result);
        }

        service.getMessageFailed = function (error)
        {
            alert(error.message);
        }

        //call the methods on the server
        service.Sum(10, 15); //id=0
        service.getMessage("Allex"); //id=1

        //call the same methods but in a batch
        service.$call({ 
            Sum: [10, 15], //id=2
            getMessage: ["Allex"] //id=3
        });

    </script>
  
</body>
</html>
HTTP TRANSFER:
Syntax:
--> data sent to Server
<-- data sent to Client
--> [{ "jsonrpc": "2.0", "method": "Sum", "params": [10, 15], "id": "0"}]
<-- [{ "jsonrpc": "2.0", "result": 20, "id": "0"}]

--> [{ "jsonrpc": "2.0", "method": "getMessage", "params": ["Allex"], "id": "1"}]
<-- [{ "jsonrpc": "2.0", "result": "Hello Allex!", "id": "1"}]

--> [{ "jsonrpc": "2.0", "method": "Sum", "params": [10, 15], "id": "2" },
     { "jsonrpc": "2.0", "method": "getMessage", "params": ["Allex"], "id": "3"}]
<-- [{ "jsonrpc": "2.0", "result": 20, "id": "2" }, 
     { "jsonrpc": "2.0", "result": "Hello Allex!", "id": "3"}]

Last edited May 11, 2010 at 5:45 PM by allex4project, version 2

Comments

No comments yet.