Ice*_*man 7 javascript python xmlhttprequest
关于使用XMLHttpRequest()时接收数据,我有两个问题.客户端是javascript.服务器端是python.
客户端
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);
Run Code Online (Sandbox Code Playgroud)
更新:我知道我应该使用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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4581 次 |
| 最近记录: |