【问题标题】:How to set up AJAX path to SimpleHTTP server using GET如何使用 GET 设置 SimpleHTTP 服务器的 AJAX 路径
【发布时间】:2014-07-21 15:46:08
【问题描述】:

我有一个存储在变量 request_str 中的字符串,我想将该数据传递给 SimpleHTTP python Web 服务器。我不确定如何将我拥有的 AJAX 实际连接到 simpleHTTP 服务器。

这是我目前设置的 ajax

$.ajax({
        url: "SOMEPLACE",
        data: {
            "key": request_str.toUpperCase()
        }
    });

这是我正在使用的 SimpleHTTP 服务器的 python 代码。

"""
Serves files out of its current directory
Dosen't handle POST request
"""

import SocketServer
import SimpleHTTPServer

PORT = 9090

def move():
    """ sample function to be called via a URL"""
    return 'hi'

class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        #Sample values in self for URL: http://localhost:9090/jsxmlrpc-0.3/
        #self.path  '/jsxmlrpc-0.3/'
        #self.raw_requestline   'GET /jsxmlrpc-0.3/ HTTP/1.1rn'
        #self.client_address    ('127.0.0.1', 3727)
        if self.path=='/move':
            #This URL will trigger our sample function and send what it returns back to the browser
            self.send_response(200)
            self.send_header('Content-type','text/html')
            self.end_headers()
            self.wfile.write(move()) #call sample function here
            return
        else:
            #serve files, and directory listings by following self.path from
            #current working directory
            SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

httpd = SocketServer.ThreadingTCPServer(('localhost', PORT),CustomHandler)

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

我之所以问如何使用 GET 进行设置,是因为服务器的设置方式。如果我能得到明确的解释,我愿意接受建议,并将其更改为 POST。有人告诉我我应该 json 数据,但我不确定这意味着什么。

期待帮助!

【问题讨论】:

    标签: python ajax simplehttpserver


    【解决方案1】:

    我假设您因为 $ 函数而使用 JQuery。参考 JQuery 文档会很有帮助:http://api.jquery.com/jquery.ajax/

    url 字段是请求将被发送到的位置。与任何 url 一样,您可以通过将 GET 变量直接输入到 url 中来传递它们:

    $.ajax() { url: 'SOMEPLACE?foo=bar&hello=world };
    

    但是 JQuery ajax 对象也有一个数据字段。从文档页面:“[数据字段] 转换为查询字符串,如果还不是字符串。它附加到 GET 请求的 url”。因此,提交请求的另一种方式,也可能是 json'ing 数据的含义是:

    $.ajax() { url: 'SOMEPLACE', data: {foo: 'bar', hello: 'world'}};
    

    另外注意默认情况下,JQuery ajax 请求是 GET。您可以使用类型字段更改它。

    $.ajax() { url: 'SOMEPLACE', data: {var1: 'val1', var2: 'val2'}, type: 'POST'};
    

    至于服务器端的python: 我不认为服务器正在寻找获取变量。它只是有一个基于 url 中路径的条件。因此,如果您一直通过 JavaScript 正确发送 GET 并且没有获得行为 - 这是因为服务器端缺少逻辑。

    看来 SimpleHTTPServer 就是这么简单。因此,为了提取 GET 变量,您必须进行一些字符串解析。考虑一些url解析函数:https://docs.python.org/2/library/urlparse.html#urlparse.parse_qs

    【讨论】:

      【解决方案2】:

      对于前端 AJAX 调用,Toby 总结的很好。如果你想做一个 GET 请求,做

      $.get("http://localhost:9090/endpoint?thing1=val", ....
      

      那么在服务器端,你需要添加一些东西

      """
      Serves files out of its current directory
      Dosen't handle POST request
      """
      
      import SocketServer
      import SimpleHTTPServer
      from urlparse import urlparse
      
      PORT = 9090
      
      def move():
          """ sample function to be called via a URL"""
          return 'hi'
      
      class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
          def do_GET(self):
              #Sample values in self for URL: http://localhost:9090/jsxmlrpc-0.3/
              #self.path  '/jsxmlrpc-0.3/'
              #self.raw_requestline   'GET /jsxmlrpc-0.3/ HTTP/1.1rn'
              #self.client_address    ('127.0.0.1', 3727)
      
          # Split get request up into components
          req = urlparse(self.path)
      
          # If requesting for /move
          if req.path =='/move':
                  #This URL will trigger our sample function and send what it returns back to the browser
                  self.send_response(200)
                  self.send_header('Content-type','text/html')
                  self.end_headers()
                  self.wfile.write(move()) #call sample function here
                  return
              else:
                  #serve files, and directory listings by following self.path from
                  #current working directory
                  SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
      
          # Else if requesting /endpoint
          elif req.path == '/endpoint':
              # Print request query
              print req.query
              # Do other stuffs...
      
      httpd = SocketServer.ThreadingTCPServer(('localhost', PORT),CustomHandler)
      
      print "serving at port", PORT
      httpd.serve_forever()
      

      基本上,您只需要添加一个区分 GET 请求的方法和一个解析它们发送的查询数据的方法。 urlparse 模块对此很有帮助。有关如何使用它的更多文档,请参阅https://docs.python.org/2/library/urlparse.html

      【讨论】:

      • 我仍然无法实现区分 GET 请求/解析查询的方法,我认为这是我的最后一步 :(
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2014-05-07
      相关资源
      最近更新 更多