WSGI:使用AJAX从Python脚本获取字符串

4 投票
4 回答
3757 浏览
提问于 2025-04-16 12:43

我正在研究WSGI,但感觉挺难的。

我想做的事情其实很简单:当我点击一个链接时,我希望从一个Python脚本中获取字符串“hello”,并在我的HTML段落元素中显示“hello”。

现在我已经写了可以用WSGI显示HTML文本的Python脚本,也就是用WSGI提供网页,但我还没有把Python、AJAX和WSGI结合起来实现上面提到的功能。

现在的问题是,当我在HTML页面中点击链接时,段落元素显示的是“error”,而不是“hello”。你觉得我哪里出错了,是在Python还是JavaScript中?

我的Python脚本下面是正确的吗?:

#!/usr/bin/env python

from wsgiref.simple_server import make_server
from cgi import parse_qs, escape

def application(environ, start_response):

   return [ "hello" ]

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    srv = make_server('localhost', 8000, application)
    srv.serve_forever()

也许是我的JavaScript和/或HTML出了问题?:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <script type="text/javascript">
    <!--
        function onTest( dest, params )
        {
            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.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById( "bb" ).innerHTML = xmlhttp.responseText;
                }
            }

            xmlhttp.open("POST",dest,true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send( params ); 
        }


    -->
    </script>
</head>

<body>

    <p id="bb"> abcdef </p>
    <a href="javascript:onTest('aaa.py', '')">Click it</a>

</body>

</html>

我测试的步骤是:
- 运行WSGI伪服务器脚本
- 打开浏览器并输入 http://localhost:8000/test.html
- 点击HTML页面中的链接,结果返回“error”

我的文件wsgi.py、aaa.py和test.html都在同一个文件夹里。

我的服务器代码是: import threading import webbrowser import os from wsgiref.simple_server import make_server

FILE = 'index.html'
PORT = 8000

def test_app(environ, start_response):

    if environ['REQUEST_METHOD'] == 'POST':

        try:
            request_body_size = int(environ['CONTENT_LENGTH'])
            request_body = environ['wsgi.input'].read(request_body_size)
        except (TypeError, ValueError):
            request_body = "0"

        try:
            response_body = str(int(request_body) ** 2)
        except:
            response_body = "error"

        status = '200 OK'
        headers = [('Content-type', 'text/plain')]
        start_response(status, headers)
        return [response_body]

    else:
        f = environ['PATH_INFO'].split( "?" )[0]
        f = f[1:len(f)]
        response_body = open(f).read()
        status = '200 OK'
        headers = [('Content-type', 'text/html'), ('Content-Length', str(len(response_body)))]
        start_response(status, headers)
        return [response_body]

def open_browser():
    """Start a browser after waiting for half a second."""

    def _open_browser():
        webbrowser.open('http://localhost:%s/%s' % (PORT, FILE))
        thread = threading.Timer(0.5, _open_browser)
        thread.start()

def start_server():
    """Start the server."""
    httpd = make_server("", PORT, test_app)
    httpd.serve_forever()


if __name__ == "__main__":
    open_browser()
    print "Now serving on Port 8000"
    start_server()

相关问题:

4 个回答

0

httpd.serve_forever()

这个命令必须放在一个函数外面。

0

这个错误看起来是来自一个Python脚本。你可以试着直接用IE浏览器或者其他浏览器打开aaa.py文件,看看是否能正常访问。

0

你没有调用 start_response 这个函数。你可以用下面这样的方式来调用它:

start_response("200 OK", [('Content-type','text/plain')])

撰写回答