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

I have two questions regarding receiving of data when using XMLHttpRequest().

Client side is in javascript.

Server side is in python.

How do I receive/process data on the python side ?

How do I respond back to HTTP request?

Client side

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);

UPDATE:

I know i should use cgi.FieldStorage() but how exactly ?My attempt ended with me getting a Server error for the post request.

解决方案

You don't necessarily use cgi.FieldStorage to handle POST data sent by an AJAX request. It is just the same as receiving a normal POST request, which means you need to get the request's body and process that.

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值