服务器以CherryPy的形式返回值给客户端

server returns value to client in CherryPy

本文关键字:返回值 客户端 CherryPy 服务器      更新时间:2023-09-26

我是web开发的新手,我正在学习使用CherryPy作为web服务的后端。我遵循本教程从客户端发送请求到服务器(我想知道是否有另一种方式?)。使用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),以便我可以在我的客户端代码中使用它。我怎么能做到呢?

好了,事情是这样的…当你使用表单时,不需要js。表单只是向cherry处理程序发送或发送数据。你需要做的是像这样使用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>

如果不明白,请告诉我。

安德鲁