I'm just new in integrating ajax http request and return a python webserver http response. I really no have an idea how to use it.
For example my web page is on another IP . like 192.168.1.1 and i will get a data or a response from 192.168.1.2 then on my view:
function test(){
$.ajax({
url : "http://192.168.1.2:8012/",
type : "GET",
success : function(data) {
alert(data);
}
});
}
now on my python web server
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()
I just want a returned data from the webserver. But i think im doing it wrong.
I think you shouldn't send data to self.wfile before sending ALL headers. And maybe you should send a 'Content-length' header to let your page know when it must stop waiting for data. Something like this:
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)
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.