Using JSONRPC with JQuery?

user1438003 picture user1438003 · Jul 22, 2012 · Viewed 8.1k times · Source

How do I get JSONRPC working properly with JQuery on the client-side, on the referenced types of calls?

To represent my attempt, I've tried to create the smallest possible test-case:

Server[1]

from txjsonrpc.web import jsonrpc
from twisted.web import server
from twisted.internet import reactor

class Math(jsonrpc.JSONRPC):
    def jsonrpc_add(self, a, b):
        return a+b

    def jsonrpc_echo(self, foo):
        return str(foo)

    def jsonrpc_hello(self):
        return u"Hello World!"

reactor.listenTCP(7080, server.Site(Math()))
reactor.run()

Client[2]

<!DOCTYPE HTML>
<html>
    <head>
        <title>Math is fun?!</title>
        <script type="text/javascript" charset="utf-8" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
        <script type="text/javascript" src="https://raw.github.com/datagraph/jquery-jsonrpc/master/jquery.jsonrpc.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $.jsonRPC.setup({
                    endPoint : 'http://localhost:7080',
                    namespace : ''
                });
                $("input#evaluate").click(function() {
                    $.jsonRPC.request('jsonrpc_echo', {
                        params : [$("textarea#input").val()],
                        success : function(data) {
                            $("<p />").text(data.result).appendTo($("p#result"));
                        },
                        error : function(data) {
                            $("<p />").text(data.error.message).appendTo($("p#result"));
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <p id="result"></p>
        <p>
            <textarea name="input" id="input"></textarea>
        </p>
        <p>
            <input name="evaluate" id="evaluate" value="evaluate" type="button" />
        </p>
    </body>
</html>
  1. Adapted from https://stackoverflow.com/a/4738563/1438003
  2. Adapted from https://github.com/filonenko-mikhail/maxima-json-rpc/blob/master/examples/js-maxima-rpc-client.html

Answer