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

2024-02-16

我有两个关于使用 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在使用 XMLHttpRequest() 时在 python 中接收 POST 数据 的相关文章

随机推荐