简体   繁体   中英

How to properly return a data and http response with python to ajax using BaseHTTPServer

I have a very simple web sever written in Python. It listens on port 8012, how can I make it deliver a simple "Hello World" webpage in html using ajax? or any possible thing to receive the return data in 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);
     }});

Once you have the response from the server is in result, you can assign it to a div element.

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

HTML:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM