2015-02-05 8 views
5

मैं जब XMLHttpRequest का उपयोग कर डेटा की प्राप्ति के बारे में दो प्रश्न हैं()। ग्राहक पक्ष जावास्क्रिप्ट में है। सर्वर पक्ष पायथन में है।जब XMLHttpRequest का उपयोग कर कैसे अजगर में पोस्ट डेटा प्राप्त करने के()

  1. मैं पाइथन पक्ष पर डेटा कैसे प्राप्त/संसाधित करूं?
  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(), लेकिन कैसे वास्तव में मेरे प्रयास मुझे पोस्ट अनुरोध के लिए एक सर्वर त्रुटि हो रही है के साथ समाप्त हुआ इस्तेमाल करना चाहिए?।

उत्तर

1

आप आवश्यक रूप से AJAX अनुरोध द्वारा भेजे गए पोस्ट डेटा को संभालने के लिए cgi.FieldStorage प्रयोग नहीं करते। यह एक सामान्य 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) 
संबंधित मुद्दे