使用dojo/request调用python函数



首先,我对web开发世界很陌生,如果这个问题过于简单,我很抱歉。我正在尝试使用python来处理AJAX请求。从阅读文档来看,Dojo/request似乎能够从我这里做到这一点,但我还没有找到任何例子来帮助实现这一点。

假设我有一个Python文件(myFuncs.py),其中包含一些函数,这些函数返回我想要从服务器获得的JSON数据。对于这个调用,我对这个文件中的一个特定函数感兴趣:

def sayhello():
   return simplejson.dumps({'message':'Hello from python world'})

我不清楚的是如何使用Dojo/request调用此函数。文档显示了这样的内容:

require(["dojo/dom", "dojo/request", "dojo/json", "dojo/domReady!"],
    function(dom, request, JSON){
        // Results will be displayed in resultDiv
        var resultDiv = dom.byId("resultDiv");
        // Request the JSON data from the server
        request.get("../myFuncs.py", {
            // Parse data from JSON to a JavaScript object
            handleAs: "json"
        }).then(function(data){
            // Display the data sent from the server
            resultDiv.innerHTML = data.message
        },
        function(error){
            // Display the error returned
            resultDiv.innerHTML = error;
        });
    }
);

这接近我想要达到的目标吗?我不明白如何指定在myFuncs.py中调用哪个函数?

您还可以创建一个小型jsonrpc服务器,并使用dojo对该服务器进行ajax调用,获取json数据。。。。

对于python方面,你可以遵循这个

jsonrpclib

对于道场,你可以试试这样的东西。。

<script>
    require(['dojox/rpc/Service','dojox/rpc/JsonRPC'],
    function(Service,JsonRpc)
    {       
        function refreshContent(){
            var methodParams = {
                envelope: "JSON-RPC-2.0",
                transport: "POST",
                target: "/jsonrpc",
                contentType: "application/json-rpc",
                services:{}
            };
            methodParams.services['myfunction'] = { parameters: [] };
            service = new Service(methodParams);
            function getjson(){
                dojo.xhrGet({
                    url: "/jsonrpc",
                    load : function(){
                        var data_list = [];
                        service.myfunction().then(
                            function(data){
                                dojo.forEach(data, function(dat){
                                    data_list.push(dat);                                            
                                });
                                console.log(data_list)
                            },
                            function(error) {
                                console.log(error);
                            }
                        );
                    }
                });
            }           
            getjson();
        }       
        refreshContent();
        });                             
    });     
</script>

我在django中使用了这种方法,我没有为rpc调用创建不同的服务器,而是使用django的url链接将调用转发到我的函数。。但是,您总是可以创建一个小型rpc服务器来执行同样的操作。。

最新更新