开发者

Python JSON RPC with jQuery - ServiceRequestNotTranslatable

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("b开发者_运维百科in/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:

$.ajax({url: "bin/controller.py",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({"jsonrpc": "2.0",
        "method": "echo", "params": ["hello",], "id": 1,
    }),
    dataType: "json",
    success: function(response) {
        alert(response.result);
    },
});

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.ajax will URL-encode it like it would for a form post (i.e. "method=echo&params=..."). So, use JSON.stringify to serialize it, and set contentType to "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.


You'd probably have an easier time implementing your service with flask, it's easy to use with jquery.

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)

@app.route('/echo')
def echo():
    return jsonify({'result': request.args.get('params')})

@app.route('/')
def index():
    return """<!doctype html><head>
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
       <script type="text/javascript">
         $.get('/echo?params=hello', function(data) {
           alert(data['result']);
         });
       </script>
       </head></html>"""

if __name__ == '__main__':
    app.run()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜