Having Trouble Getting SimpleHTTPRequestHandler to respond to AJAX

和自甴很熟 提交于 2019-12-20 23:28:16

问题


I recently tried implementing the SimpleHTTPRequestHandler to accept AJAX requests according to this.

Although everything seems to work as far as receiving the request from the client, I cannot send anything back to the client, when I try to self.wfile.write("foo"), I get a response back in the client; however, the response text from the XmlObject is completely blank!?!

If anybody can shed any light on this, that would be great!

EDIT: I think my AJAX call is structured correctly since I am getting responses from Python (I've checked in debug mode); however, I am not getting any message back responseText when I get an object back.


回答1:


Make sure your response has a send_header() with a content type. I have seen AJAX requests get confused without this. You can also try switching your POST to a GET for debugging and make sure the browser can see the content.

Here is a simple HTTP example for returning XML if you point your query or browser to 127.0.0.1/test:

import SimpleHTTPServer, SocketServer
import urlparse

PORT = 80

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
   def do_GET(self):

       # Parse query data & params to find out what was passed
       parsedParams = urlparse.urlparse(self.path)
       queryParsed = urlparse.parse_qs(parsedParams.query)

       # request is either for a file to be served up or our test
       if parsedParams.path == "/test":
          self.processMyRequest(queryParsed)
       else:
          # Default to serve up a local file 
          SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self);

   def processMyRequest(self, query):

       self.send_response(200)
       self.send_header('Content-Type', 'application/xml')
       self.end_headers()

       self.wfile.write("<?xml version='1.0'?>");
       self.wfile.write("<sample>Some XML</sample>");
       self.wfile.close();

Handler = MyHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()


来源:https://stackoverflow.com/questions/11748372/having-trouble-getting-simplehttprequesthandler-to-respond-to-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!