使用 XMLHttpRequest() 时如何在 python 中接收 POST 数据

How to receive POST data in python when using XMLHttpRequest()

我有两个关于在使用 XMLHttpRequest() 时接收数据的问题。 客户端位于 javascript。 服务器端在 python.

  1. 如何在 python 端 receive/process 数据?
  2. 如何响应 HTTP 请求?

客户端

    var http = new XMLHttpRequest();
    var url = "receive_data.cgi";
    var params = JSON.stringify(inventory_json);
    http.open("POST", url, true);

    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    http.onreadystatechange = function() {
    //Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }   
    }
    http.send(params);

更新: 我知道我应该使用 cgi.FieldStorage() 但究竟如何?我的尝试以 post 请求的服务器错误结束。

您不一定要使用 cgi.FieldStorage 来处理由 AJAX 请求发送的 POST 数据。它与接收正常的 POST 请求一样,这意味着您需要获取请求的主体并对其进行处理。

import SimpleHTTPServer
import json

class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers.getheader('content-length'))        
        body = self.rfile.read(content_length)
        try:
            result = json.loads(body, encoding='utf-8')
            # process result as a normal python dictionary
            ...
            self.wfile.write('Request has been processed.')
        except Exception as exc:
            self.wfile.write('Request has failed to process. Error: %s', exc.message)