使用XMLHttpRequest()时如何在python中接收POST数据
How to receive POST data in python when using XMLHttpRequest()
关于使用XMLHttpRequest()时接收数据,我有两个问题。客户端使用javascript。服务器端在python中。
- 如何在python端接收/处理数据
- 如何回复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)
相关文章:
- 通过python擦除Vine数据
- 如何将 JSON 数据从 python 返回到 javascript
- 将数据从 Python 发送到 Javascript (JSON)
- 使用回发数据抓取页面 javascript Python Scrapy
- 如何使用由Javascript填充的Python从网站获取数据
- javascript和python返回的相同数据结构在d3.js中表现不同
- python使用javascript提交通过POST发送数据
- 如何在没有web服务器的情况下将变量数据从Python传输到Javascript
- 使用XMLHttpRequest()时如何在python中接收POST数据
- 将数据从Javascript传递回Python
- 使用 JSON 在 python 和 javascript 之间传递数据
- 我无法在谷歌图表的代码 javascript 中获取 json 数据(项目 Python Hello Dashboard
- 如何通过“POST”方法将数据从Javascript传递到Python
- Python - 从服务器获取数据 (ajax) - 'str' 对象不是可调用的错误
- 数据从Javascript往返于Redis(通过Python)并返回
- 从Django到Javascript的Python数据
- 使用Django模板(列表和dicts)将Python数据结构转换为js数据结构
- 在web2py中传递python数据给javascript
- 当python还在运行时,在node.js上显示python数据
- 使用jinja2模板(列表和dicts)将Python数据结构转换为js数据结构