Python JSON RPC与jQuery - ServiceRequest不可翻译
我正在用 Python 编写一个网页应用,使用 JSON-RPC 的实现 - http://json-rpc.org/wiki/python-json-rpc 在服务器端,客户端则用 jQuery 的 ajax API。这是我第一次在 Python 中实现 JSON 服务,所以我从上面提到的网站复制了一个例子(在 Apache 2.2 上运行 CGI):
#!/usr/bin/env python
from jsonrpc import handleCGI, ServiceMethod
@ServiceMethod
def echo(msg):
return msg
if __name__ == "__main__":
handleCGI()
使用提供的 Python ServiceProxy 类作为客户端(在控制台中)一切都运行得很好:
from jsonrpc import ServiceProxy
s = ServiceProxy("http://localhost:8080/mypage/bin/controller.py")
print s.echo("hello")
但是当我尝试在 Firebug 控制台中使用 jQuery 进行 ajax 调用(在我的页面上下文中)时:
var jqxhr = $.getJSON("bin/controller.py", {"params": ["hello"], "method": "echo", "id": 1}, function(data) { alert('success!'); });
我总是收到这个错误:
{"error":{"message":"","name":"ServiceRequestNotTranslatable"},"result":null,"id":""}
我哪里做错了?
2 个回答
3
你可能会发现用 flask 来实现你的服务会更简单一些,因为 它和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()
4
下面是如何在jQuery中进行JSON RPC调用的方法:
$.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);
},
});
我们需要使用HTTP POST方法,这样才能发送数据。
发送的数据实际上需要是一个用JSON格式编码的字符串。如果你直接传一个对象,jQuery.ajax
会把它转换成URL编码,就像表单提交那样(比如说变成"method=echo¶ms=...")。所以,我们需要用JSON.stringify
把对象转换成字符串,并且把contentType
设置为"application/json"
,这样就能告诉服务器我们发送的是JSON格式的数据,而不是"application/x-form-urlencoded"
。
设置dataType: "json"
只是告诉jQuery要把返回的数据(当然也是JSON格式的)转换回对象,这样我们就可以像操作对象一样来访问它。