2012-05-23 62 views
2

可能重複:
Post JSON to Python CGIAJAX發佈到Python CGI

我有安裝的Apache2和Python工作。

雖然我有問題。我有兩頁。

一個Python頁面,另一個Html頁面與JQuery 我couldent pase Src的谷歌jquery鏈接。

有人可以告訴我如何讓我的ajax文章正常工作。

$(function() 
    { 
     alert('Im going to start processing'); 

     $.ajax({ 
      url: "saveList.py", 
      type: "post", 
      data: {'param':{"hello":"world"}}, 
      dataType: "application/json", 
      success : function(response) 
      { 
       alert(response); 
      } 
     }); 
    }); 

而Python代碼

import sys 
import json 

def index(req): 
    result = {'success':'true','message':'The Command Completed Successfully'}; 

    data = sys.stdin.read(); 

    myjson = json.loads(data); 

    return str(myjson); 
+1

請不要打開你的問題的多個副本。 –

回答

17

下面是一個例子HTML文件,並伴隨蟒蛇CGI腳本,它應該讓你去:

使用這個網站:

<html> 
    <head> 
     <meta http-equiv="content-type" content="text/html; charset=utf-8"> 

     <title>test</title> 
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
     <script> 

      $(function() 
      { 
       $('#clickme').click(function(){ 
        alert('Im going to start processing'); 

        $.ajax({ 
         url: "/scripts/ajaxpost.py", 
         type: "post", 
         datatype:"json", 
         data: {'key':'value','key2':'value2'}, 
         success: function(response){ 
          alert(response.message); 
          alert(response.keys); 
         } 
        }); 
       }); 
      }); 

     </script> 
    </head> 
    <body> 
     <button id="clickme"> click me </button> 
    </body> 

</html> 

和此腳本:

#!/usr/bin/env python 

import sys 
import json 
import cgi 

fs = cgi.FieldStorage() 

sys.stdout.write("Content-Type: application/json") 

sys.stdout.write("\n") 
sys.stdout.write("\n") 


result = {} 
result['success'] = True 
result['message'] = "The command Completed Successfully" 
result['keys'] = ",".join(fs.keys()) 

d = {} 
for k in fs.keys(): 
    d[k] = fs.getvalue(k) 

result['data'] = d 

sys.stdout.write(json.dumps(result,indent=1)) 
sys.stdout.write("\n") 

sys.stdout.close() 

點擊按鈕後,你可以看到CGI腳本返回:

{ 
"keys": "key2,key", 
"message": "The command Completed Successfully", 
"data": { 
    "key2": "value2", 
    "key": "value" 
}, 
"success": true 
} 
+0

我得到undefined而不是它應該返回的內容 – erdomester

+0

我得到「不支持的方法(」post「)」,無論我是在'localhost'還是在Google Cloud上運行它。 – Randoms