2012-04-19 30 views
0

我一直在準備從PHP遷移出來,並決定爲我的下一個項目使用Python,我設法讓自己完全停留在某些東西上,並且我想知道是否有人可以提供幫助我出去了。從jQuery .getJSON傳遞JSON到Python

如果我執行:

$.getJSON('test.php', { testdata: 'hello world' }) 

在 'test.php的' 我可以使用

$_GET['testdata'] 

檢索 '世界你好'。

我似乎無法找到test.py等價的:

$.getJSON('test.py', { testdata: 'hello world' }) 

我所看到的代碼在網上公佈有關或request.GET中以os.environment獲取數據,但我沒能做出任何配置工作。有人會有什麼建議嗎?

我很新開發,所以如果我錯過了一些顯而易見的道歉。

類感謝

+1

你如何在服務器上執行'test.py'? – 2012-04-19 16:17:18

+0

我不太清楚你的意思,道歉,我對這一切都很陌生。我已經配置了服務器,使用cgi作爲處理器,並將chmoded test.py設置爲755.我運行的是默認的apache和python版本,如果有幫助的話,將附帶osx lion。 – 2012-04-19 16:26:01

回答

2

這工作對我說:

import cgi 
import cgitb  #this... 
cgitb.enable() #..and this are not really necessary but helps debuging 

data= cgi.FieldStorage() 

#remove this commant to take a look in the data received by python 
#print data 

#here you can retrieve the value passed by ajax 
print data['testdata'].value 

我希望它爲你工作。

+0

完美的作品,謝謝! – 2012-04-19 17:05:05

0

The cgi documentation包含有關如何在Python CGI腳本中檢索GET和POST變量的信息。

+0

謝謝,這真的很有幫助 - 我的目標是讓mod_wsgi接下來運行,在這種情況下,現場存儲仍然是正確的路線? – 2012-04-19 16:44:19