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

问题描述 投票:7回答:1

关于使用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(),但究竟是怎么回事?我的尝试以我的邮件请求收到服务器错误而告终。

javascript python xmlhttprequest
1个回答
0
投票

您不一定使用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)
© www.soinside.com 2019 - 2024. All rights reserved.