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

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

本文关键字:python 数据 POST XMLHttpRequest 使用      更新时间:2023-09-26

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

  1. 如何在python端接收/处理数据
  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(),但具体如何?我的尝试结束了,因为我收到了发布请求的服务器错误。

您不一定要使用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)