How to get POST data in python using XMLHttpRequest ()

I have two questions regarding receiving data when using XMLHttpRequest (). The client side is in javascript. The server side is in python.

  • How do I get / process data on the python side?
  • How do I respond to an 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 up getting a server error for a send request.

+5
source share
1 answer

You do not necessarily use cgi.FieldStorage to process POST data sent on AJAX request. This is the same as receiving a regular POST request, which means that you need to receive the request body and process it.

 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) 
+1
source

Source: https://habr.com/ru/post/1212745/


All Articles