【问题标题】:How to receive POST data in python when using XMLHttpRequest()使用 XMLHttpRequest() 时如何在 python 中接收 POST 数据
【发布时间】:2023-04-07 07:10:01
【问题描述】:

我有两个关于使用 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】:

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

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      相关资源
      最近更新 更多