【问题标题】:server returns value to client in CherryPy服务器在 CherryPy 中向客户端返回值
【发布时间】:2015-12-07 04:51:59
【问题描述】:

我是 Web 开发的新手,我正在学习使用 CherryPy 作为 Web 服务的后端。我正在关注这个tutorial 将请求从客户端发送到服务器(我想知道是否还有其他方法?)。使用cherrypy用python编写的服务器然后处理请求并应该向客户端(html和js)返回一个值(变量),这就是我卡住的地方。服务器如何将变量返回给客户端?我很困惑,我没有看到任何解释这一点的示例或教程。

比如我的客户端有这段代码(保存为index.html):

<!DOCTYPE html>
<html>
<head></head>
<body>
<form method="get" action="generate">
<input type="text" value="8" name="length" />
<button type="submit">Give it now!</button>
</form>
</body>
</html>

我的服务器端是:

import random
import string

import cherrypy

class StringGenerator(object):
    @cherrypy.expose
    def index(self):
        return open("index.html")

    @cherrypy.expose
    def generate(self, length=8):
        ranNum = ''.join(random.sample(string.hexdigits, int(length)))
        return ranNum

if __name__ == '__main__':
    cherrypy.quickstart(StringGenerator())

所以当我提交表单时,将调用服务器端的 generate() 函数,并将我提交的值作为参数。但我不希望网页现在只显示返回值,我希望服务器将返回值发送回客户端(html 和 js),以便我可以在客户端代码中使用它。我该怎么办?

【问题讨论】:

    标签: javascript jquery python html cherrypy


    【解决方案1】:

    好的,这是怎么回事...当您使用表单时,不需要 js。该表单只是向cherrypy 处理程序发布或发送数据。你想要做的就是用 js 或 jquery 来做这样的事情......

    <form method="get" action="generate();">
    </form>
    <script>function generate() {
    var xmlhttp;
    
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }
    
    else{ // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlhttp.open("POST","generate",true);
    xmlhttp.send();
    
    // your response will be here.
    xmlDoc=xmlhttp.responseXML;
    };</script>
    

    如果这没有意义,请告诉我。

    安德鲁

    【讨论】:

      猜你喜欢
      • 2015-11-22
      • 1970-01-01
      • 2021-07-19
      • 2020-08-27
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多