2011-03-01 57 views
3

我正在鑽研WSGI &,這很難。WSGI:使用AJAX從python腳本獲取字符串

我所試圖做的東西很簡單:當我點擊一個鏈接我想從我的HTML段落元素python腳本&顯示「你好」的字符串「hello」。

現在我已經制作了顯示HTML文本的WSGI python腳本,即,使用WSGI python提供頁面,但不使用Python,AJAX & WSGI一起用於上述目的。

現在發生了什麼是當我點擊我的HTML頁面中的鏈接,段落元素顯示「錯誤」而不是「你好」。你認爲我哪裏錯了?在Python或JavaScript?

下面是正確的?:

#!/usr/bin/env python 

from wsgiref.simple_server import make_server 
from cgi import parse_qs, escape 

def application(environ, start_response): 

    return [ "hello" ] 

if __name__ == '__main__': 
    from wsgiref.simple_server import make_server 
    srv = make_server('localhost', 8000, application) 
    srv.serve_forever() 

也許我的Python腳本的我的JavaScript & /或HTML我在哪裏錯了?:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 

    <script type="text/javascript"> 
    <!-- 
     function onTest(dest, params) 
     { 
      var xmlhttp; 

      if (window.XMLHttpRequest) 
      {// code for IE7+, Firefox, Chrome, Opera, Safari 
       xmlhttp=new XMLHttpRequest(); 
      } 
      else 
      {// code for IE6, IE5 
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
      } 

      xmlhttp.onreadystatechange=function() 
      { 
       if (xmlhttp.readyState==4 && xmlhttp.status==200) 
       { 
        document.getElementById("bb").innerHTML = xmlhttp.responseText; 
       } 
      } 

      xmlhttp.open("POST",dest,true); 
      xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
      xmlhttp.send(params); 
     } 


    --> 
    </script> 
</head> 

<body> 

    <p id="bb"> abcdef </p> 
    <a href="javascript:onTest('aaa.py', '')">Click it</a> 

</body> 

</html> 

步驟我需要對其進行測試:
- 運行wsgi假服務器腳本
- 打開瀏覽器&類型http://localhost:8000/test.html
- 點擊& HTML頁面的鏈接得到「錯誤」回

我的文件wsgi.py,aaa.py &的test.html都在同一個文件夾。

我的服務器:從wsgiref.simple_server進口make_server

FILE = 'index.html' 
PORT = 8000 

def test_app(environ, start_response): 

    if environ['REQUEST_METHOD'] == 'POST': 

     try: 
      request_body_size = int(environ['CONTENT_LENGTH']) 
      request_body = environ['wsgi.input'].read(request_body_size) 
     except (TypeError, ValueError): 
      request_body = "0" 

     try: 
      response_body = str(int(request_body) ** 2) 
     except: 
      response_body = "error" 

     status = '200 OK' 
     headers = [('Content-type', 'text/plain')] 
     start_response(status, headers) 
     return [response_body] 

    else: 
     f = environ['PATH_INFO'].split("?")[0] 
     f = f[1:len(f)] 
     response_body = open(f).read() 
     status = '200 OK' 
     headers = [('Content-type', 'text/html'), ('Content-Length', str(len(response_body)))] 
     start_response(status, headers) 
     return [response_body] 

def open_browser(): 
    """Start a browser after waiting for half a second.""" 

    def _open_browser(): 
     webbrowser.open('http://localhost:%s/%s' % (PORT, FILE)) 
     thread = threading.Timer(0.5, _open_browser) 
     thread.start() 

def start_server(): 
    """Start the server.""" 
    httpd = make_server("", PORT, test_app) 
    httpd.serve_forever() 


if __name__ == "__main__": 
    open_browser() 
    print "Now serving on Port 8000" 
    start_server() 

回答

0

你不是叫start_response 進口線程 進口web瀏覽器 進口OS 。使用如下呼叫:

start_response("200 OK", [('Content-type','text/plain')]) 
+0

謝謝。如果我服務我自己的頁面,我運行該腳本,然後在瀏覽器中輸入http:// localhost:8000,但在我運行我的假的wsgi服務器時不起作用,然後在瀏覽器中運行我的html頁面並點擊鏈接。我仍然得到「錯誤」。也許我的服務器是問題(請參閱服務器問題)? – Mack 2011-03-01 04:15:53

+0

哪裏?或者這個答案變得過時了?我在上面的代碼片段中看到'start_response()',所以我不確定你的建議。 – dwanderson 2015-01-14 17:06:22

+0

@dwanderson他在我的回答幫助下編輯了他的問題。請參閱https://stackoverflow.com/posts/5150339/revisions。 – 2015-01-15 07:02:15

0

錯誤似乎來自python腳本。檢查aaa.py是否可以直接訪問您的IE或其他瀏覽器。

+0

從@Matthew Flaschen回答,python腳本在我運行它時運行,然後鍵入http ...:8000,所以我認爲腳本沒問題,但我不確定我應該提供什麼服務? – Mack 2011-03-01 04:19:57

+0

似乎有點有線,並且我建議你在test.html中單擊你的錨後使用firefox來監視網絡。現在您使用'POST'方法上傳數據,您是否可以嘗試使用'GET'? – Kardel 2011-03-02 18:11:16

0

httpd.serve_forever()

已經是一個功能塊

0

不能使用 「aaa.py」 的帖子的網址在這裏之外。然後服務器會查看這個文件的根目錄。例如本地主機/ aaa.py。您必須從服務器根目錄(不包含服務器根路徑)提供完整路徑,例如:如果文件位於/var/www/wsgi-scripts/aaaa.py 那麼url應該是/wsgi-scripts/aaaa.py。