I’m writing a web application using python JSON-RPC implementation – http://json-rpc.org/wiki/python-json-rpc on server side and jQuery axaj API on client side.
This is my first JSON service implementation in python, so I’ve copied the example from mentioned site (CGI run on Apache 2.2):
#!/usr/bin/env python
from jsonrpc import handleCGI, ServiceMethod
@ServiceMethod
def echo(msg):
return msg
if __name__ == "__main__":
handleCGI()
Everything works fine with supplied python ServiceProxy class as a client (in console):
from jsonrpc import ServiceProxy
s = ServiceProxy("http://localhost:8080/mypage/bin/controller.py")
print s.echo("hello")
But when I try to make an ajax call using jQuery in firebug console (in context of my page):
var jqxhr = $.getJSON("bin/controller.py", {"params": ["hello"], "method": "echo", "id": 1}, function(data) { alert('success!'); });
I constantly receive this error:
{"error":{"message":"","name":"ServiceRequestNotTranslatable"},"result":null,"id":""}
What am I doing wrong?
This is how to make a JSON RPC call in jQuery:
Needs to be HTTP POST method so we can send data.
The data actually needs to be a string in JSON encoding. If you pass an object,
jQuery.ajaxwill URL-encode it like it would for a form post (i.e. “method=echo¶ms=…”). So, useJSON.stringifyto serialize it, and setcontentTypeto"application/json"to signify that we’re sending JSON instead of"application/x-form-urlencoded".Setting
dataType: "json"just tells jQuery to unserialize the returned data (also JSON format, of course), so we can access it as an object.