使用jquery调用web2py jsonrpc服务

时间:2014-09-03 06:54:55

标签: jquery web2py

我正在尝试使用jQuery对我的Web服务进行ajax jsonrpc调用,如下所示:

   $(document).ready(function() {
    $("#btnNext,#btnPrevious").click(function() {
        var req = {
            jsonrpc: "2.0",
            method: "nextprevexample",
            id: (new Date).getTime()
        };
        req.res = {
            name: 'aajas'
        };
        $.ajax({
            url: "http://127.0.0.1:8000/adv01/default/call/jsonrpc",
            data: JSON.stringify(req),
            dataType: "json",
            type: "POST",
            contentType: "application/json",
            success: function(rpcRes) {
                alert(rpcRes.result);
                $("#lblexample").text(rpcRes.result[1]);
                $("#txtexamplereviewed").val(rpcRes.result[1]);
            },
            error: function(err, status, thrown) {
                alert(thrown); //alert(status);alert(thrown);
            }
        });
        return false;
    });
});

我正在尝试在我的web2py网络服务中访问它。 Web服务的代码如下:

@service.json   
@service.jsonrpc    
def nextprevexample():    
    print request.post_vars
    exampleid,exampletext=getcorrespondingexample()
    return exampleid,exampletext

但问题是我在post_vars中没有得到任何东西。

我试图搜索整个请求对象,找到任何可以给我发布数据但找不到的属性。

如果我在这里做错了,请告诉我。

1 个答案:

答案 0 :(得分:0)

OP也在Google Groups中发布了此消息,结果如下:

谢谢安东尼。我检查了它,因为我的Web服务定义错误而引发了错误。另外,我的jQuery代码不正确。我修复了它,它开始工作。在这里,我发布我的代码,如果它可以帮助将来任何人参考。

jquery的:

function nextprevajaxcall(nextprevindicator)

{
  var req = {jsonrpc:"2.0", method: "nextprevexample",id:(new Date).getTime()};     
  req.params=[nextprevindicator];

  $.ajax({        
    url: "http://127.0.0.1:8000/adv01/default/call/jsonrpc",
    data: JSON.stringify(req),
    dataType: "json",
    type: "POST",
    contentType: "application/json",
    success: function(rpcRes) {            
        //alert(JSON.stringify(rpcRes));

        $("#lblexample").text(rpcRes.result[1]);
        $("#txtexamplereviewed").val(rpcRes.result[1]);
    },
    error: function(err, status, thrown) {          
      alert(thrown);//alert(status);alert(thrown);
    }  
  });
}

$(document).ready(function(){  
  $("#btnNext").click(function(){        
    nextprevajaxcall(1);
    return false;
  });
  $("#btnPrevious").click(function(){        
    nextprevajaxcall(0);
    return false;
  });
});

web2py controller:

@service.json   
@service.jsonrpc    
def nextprevexample(nextprevindicator):
    #print nextprevindicator    
    exampleid,exampletext=getcorrespondingexample(nextprevindicator)    
    return exampleid,exampletext

请注意,我们在request.params中发送的任何jquery代码都会作为参数发布到web2py jsonrpc web服务。

相关问题