AJAX HTTP请求和Python Web服务器HTTP响应返回

时间:2014-02-20 09:31:01

标签: python ajax

我刚刚整合了ajax http请求并返回python webserver http响应。我真的不知道如何使用它。

例如我的网页在另一个IP上。像192.168.1.1,我将从192.168.1.2获得数据或响应 然后在我看来:

function test(){
    $.ajax({
        url : "http://192.168.1.2:8012/",
        type : "GET",
        success : function(data) {
             alert(data);
        }
    });
}

现在在我的python web服务器上

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

db = MySQLdb.connect("localhost","root","password","schema" )
cnn = db.cursor()


class MyHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        global cnn, sql

        self.wfile.write("Cannot GET "+self.path)
        print "test"
        self.send_response(200, "testing")
        self.send_header('Content-type', 'xml')
        self.end_headers()
        self.wfile.write("testing")


    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()

我只想从网络服务器返回数据。但我认为我做错了。

1 个答案:

答案 0 :(得分:1)

我认为你不应该在发送ALL头之前将数据发送到self.wfile。也许您应该发送一个“内容长度”标题,以便在必须停止等待数据时让您的页面知道。像这样:

data="Cannot GET "+self.path
self.send_response(200)
self.send_header('Content-type','text/xml')
self.send_header('Content-length',str(len(data))
self.end_headers()
self.wfile.write(data)