jQuery jsonrpc 2.0通过.ajax()调用得到正确的响应,但不起作用?

通过jquery到Tornado Web服务器的jsonrpc 2.0调用获得“200 OK”http响应,我的网络嗅探器将解码后的响应显示为包含

{ “jsonrpc”: “2.0”, “错误”:NULL, “结果”:3500, “ID”: “jsonrpc”}

即有效的jsonrpc 2.0响应。 3500也是正确的结果,RPC是一个简单的添加function。

但是,firebug不会显示响应,并且不会触发.ajax 成功回调。 触发了.ajax() 错误完整的回调,但没有给出任何关于问题的线索。 这是触发ajax()调用的index.html。

$(document).ready(function(){ $.ajax({ url: 'http://localhost:8080', data: JSON.stringify ({jsonrpc:'2.0',method:'add', params:[1400,2100],id:"jsonrpc"} ), // id is needed !! type:"POST", dataType:"json", success: function (result) { alert("ok"); }, error: function (err,status,thrown) { alert ("this syntax sucks!! " + " ERROR: " + err + " STATUS: " + status + " " + thrown ); }, complete: function (xhr,status) { alert('Complete=> showing status as: '+ status); data = $.parseJSON(xhr.responseText); alert (data); } }); }); 

我发现问题是使用Firefox“File Open”打开index.html而不是让我的web服务器向我发送index.html(通过浏览http:// localhost:8080 )

下面是一个完整的工作示例,用于进行JSON RPC调用并使用简单警报显示结果。 RPC是一个基本的附加function。

要看到它的实际效果:

  • 保存index.html(2)和webserver.py(1)。 编辑webserver.py以反映index.html的位置

  • 启动webserver.py(chmod a + x webserver.py.sudo ./webserver.py)

  • 启动Firefox并浏览到localhost:8080。 这将加载index.html,触发ajax()调用并使用警报显示结果。

(1)Web服务器是使用tornadorpc模块并用Python编写的Tornado。 这里是:

 #! /usr/bin/python2.6 import tornado.httpserver import tornado.ioloop import tornado.web from tornadorpc.json import JSONRPCHandler from tornadorpc import private, start_server class MainHandler(tornado.web.RequestHandler): def get(self,upath): self.write( open('/home/travis/EXPLORE/webApps/index.html').read() ) class Tree(object): def power(self, base, power, modulo=None): return pow(base, power, modulo) def _private(self): # Won't be callable return False class Handler(JSONRPCHandler): print ('In Handler()...') tree = Tree() def add(self, x, y): print ('add() method called...') return x+y def ping(self, obj): return obj # Order is important here.. first matched handler in array is used !! handlers = [ ('/RPC2',Handler), (r"/(.*)", MainHandler), ] start_server(handlers, port=8080) 

(2)index.html使用jquery的ajax()方法对添加远程过程进行JSONRPC调用。 确保将其保存到的位置与(1)中的Web服务器尝试从中读取其内容的路径相匹配。

       

jQuery JSON RPC 2.0 demo