2015-02-05 25 views
5

XMLHttpRequest() kullanırken verilerin alınmasıyla ilgili iki sorum var. İstemci tarafı javascript'te. Sunucu tarafı python'tadır.XMLHttpRequest() kullanırken python'da POST verileri nasıl alınır()

  1. Python tarafındaki verileri nasıl alırım/işlerim?
  2. HTTP isteğine nasıl yanıt veririm?

İstemci tarafı

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

GÜNCELLEME: Ben cgi.FieldStorage() ancak tam olarak nasıl girişimim bana sonrası isteği için bir sunucu hatası alıyorum ile sona erdi kullanmalıdır biliyor musunuz?.

cevap

1

Bir AJAX isteği tarafından gönderilen POST verilerini işlemek için cgi.FieldStorage'u kullanmanız gerekmez. Bu, normal bir POST isteğinin alınmasıyla aynıdır, yani isteğin gövdesini almanız ve bunu işlemeniz gerekir.

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) 
İlgili konular