0

我有一个存储在变量 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 数据,但我不确定这意味着什么。

期待帮助!

4

2 回答 2

1

For the front end AJAX call, Toby summarized it nicely. If you wanted to do a GET request, do

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

Then on the server side, you need to add a couple of things

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

Basically, you just need to add a method of differentiating GET requests and a method for parsing the query data they are sending. The urlparse module is helpful for this. For more documentation on how to use it, see https://docs.python.org/2/library/urlparse.html

于 2014-07-31T15:11:02.457 回答
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

于 2014-07-28T13:56:34.233 回答