2012-03-09 20 views
0

我想從網頁獲取結果,從dom發送爲json通過ajax,然後將這些數據發送到python腳本,運行它,然後將新結果作爲json返回。我被告知一個運行gearman的php腳本將是一個很好的選擇,但我仍然不確定這是如何工作的。如何通過網絡服務器運行python腳本並將結果返回給javascript?

+0

你可以使用PHP來調用系統的腳本和程序,並應* *捕獲任何從這些腳本回顯回去吧。 '$ return = system(/path/to/script.py);'只要腳本可以由你的web服務器執行。 – 2012-03-09 23:25:29

+0

製作一個python cgi並閱讀post/get參數。 – epascarello 2012-03-09 23:41:47

+3

爲什麼要通過PHP腳本看起來似乎是個好主意?只需在服務器上運行python腳本。 – geoffspear 2012-03-09 23:51:40

回答

0

將您的Python腳本放入您的CGI目錄,並使用腳本中的cgijson模塊從post/get參數中讀取AJAX。當然你可以從PHP做一個系統調用來運行一個Python腳本,但我想不出你爲什麼會這麼做。

1

下面是使用twistedjquery我的例子。

#!/usr/local/bin/python 
import json 
import time 

from twisted.internet import reactor 
from twisted.web.server import Site 
from twisted.web.resource import Resource 


class DataPage(Resource): 
     isLeaf = True 

     def render_GET(self, request): 

       htmlFile = open("template.html") 
       html = open("template.html").read() 
       htmlFile.close() 

       return html 

     def render_POST(self, request): 
       print request.args 
       data = request.args['data'][0] 
       print data 
       return json.dumps(data[::-1]) 

resource = DataPage() 
factory = Site(resource) 
reactor.listenTCP(38123, factory) 
reactor.run() 

和HTML

<html> 
<head> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
     function flipData(){ 

      $.post("http://localhost:38123/", { data: "makeitbackwards" }, 
      function(data){ 
        alert(data); 
      }, "json"); 
     } 
    </script> 
</head> 
<body> 
<a href="javascript:void(0)" onclick="flipData()">Get Time</a> 
</body> 
</html> 
相關問題