2015-02-05 314 views
5

當使用XMLHttpRequest()時,有兩個有關接收數據的問題。 客戶端在javascript中。 服務器端是在python中。如何在使用XMLHttpRequest()時在Python中接收POST數據()

  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(),但究竟如何我嘗試用我得到一個服務器錯誤POST請求結束?

回答

1

您不一定使用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) 
相關問題