如何通过BaseHTTPServer在Python中正确向Ajax返回数据和HTTP响应

1 投票
1 回答
1143 浏览
提问于 2025-04-17 20:33

我有一个用Python写的非常简单的网页服务器。它在8012端口上监听,我该如何让它通过ajax发送一个简单的“Hello World”网页呢?或者有没有其他方法可以接收返回的html数据?

#Copyright Jon Berg , turtlemeat.com

import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import MySQLdb
from lxml import etree
from lxml.builder import E as buildE
import urllib

global db, cnn

class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        global cnn, sql

        module_name = "UMESSAGE WEBSERVER"

        #parse path data
        val = self.path.split('/')
        type = val[1]
        #val_rna = val[2]
        #val_imsi = val[3]

    if type == 'test':
        self.send_response(202, "Processing...")
        self.send_header('Content-type', 'xml')
        self.end_headers()
        self.wfile.write("testing")
        print "test"
    else:
        err = self.wfile.write("Cannot GET "+self.path)
        print "else"
        self.send_response(200, "else")
        self.send_header('Content-type', 'xml')
        self.end_headers()
        self.wfile.write("else")

    def do_POST(self):
    global rootnode
    try:
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        if ctype == 'multipart/form-data':
            query=cgi.parse_multipart(self.rfile, pdict)
        self.send_response(301)

        self.end_headers()
        upfilecontent = query.get('upfile')
        print "filecontent", upfilecontent[0]
        self.wfile.write("<HTML>POST OK.<BR><BR>");
        self.wfile.write(upfilecontent[0]);

    except :
        pass

def main():
try:
    server = HTTPServer(('', 8012), MyHandler)
    print 'started httpserver...'
    server.serve_forever()
except KeyboardInterrupt:
    print '^C received, shutting down server'
    server.socket.close()

if __name__ == '__main__':
    main()

html/ajax

$.ajax({
     url:"http://192.xxx.x.x/test",
     type: "POST",
     success:function(result){
     alert(result);
     }});

1 个回答

0

一旦你从服务器得到了响应,结果会保存在一个叫做result的地方。你可以把这个结果放到一个div元素里。

举个例子:
$.ajax({ type: "POST", url: "/some_url", data: put-some-data, success: function(msg){ $("#data").html(msg) } }) });

HTML:

<div id="data"></div> 

撰写回答