2015-05-19 48 views
1

我知道這可能是微不足道的,但我似乎無法弄清楚如何將我的網頁上的用戶提交的數據發送到服務器端。我正在製作一個簡單的網絡應用程序,它接收用戶的單詞,然後使用Python來計算服務器端的音節數。使用Flask的表單處理

我渲染頁面使用燒瓶:

@app.route('/') 
def hello(): 
    webPage = open('pg.html','r') 
    return webPage.read() 

JavaScript我有一個form

<form method="get"><br><br> 
    Enter a Word: <br> 
<input type="text" name="name"><br><br> 
<input type="submit" value="Submit"> 
     </form> 

當用戶提交一個詞來這種形式,我怎麼跟Python找回?

我讀過約​​和POST方法,但我仍然很困惑。

+1

表單是對操作的「POST」請求。看看[this](http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms) –

回答

0

考慮到你知道關於GETPOST,這裏是重要的位。

顯示家庭(你好)頁面現在

from flask import render_template 

@app.route('/') 
def hello(): 
    return render_template('hello.html') 

,在hello.html(注意動作和方法):如果你注意到

<html> 
    <head></head> 
    <body> 
     <form method="POST" action="/testpost"> 
      Enter a Word: <br> 
      <input type="text" name="name"><br><br> 
      <input type="submit" value="Submit"> 
     </form> 
    </body> 
</html> 

,方法是POST這意味着,你的數據是作爲POST發送到服務器的。現在處理POST要求,我們可以考慮以下因素:

現在POST處理

@app.route('/testpost', methods = ['POST']) 
def postTesting(): 
    name = request.form['name'] 
    print name #This is the posted value 

你看,request.form包含解析表單數據。

+0

現在,有一個問題,究竟是什麼action =「/ testpost 「幹嘛?是否創建一個新頁面? –

+0

@DeseanAbraham這是你的'POST'的URL。 (一個程序的URI)所以,當你說:'action =「/ testpost」',它表示一個URL爲帶有POST數據的「http:// localhost/testpost」。 (考慮localhost是你的託管服務器) –

+0

如果你想發送數據,這是必要的。 (不是唯一的方式)。 「testpost」只是一個例子。你可以提供你想要的任何URI名稱。它會將您的數據發佈到該URI。檢查[this](http://stackoverflow.com/questions/3477333/what-is-the-difference-between-post-and-get)和[this](https://developer.mozilla.org/en- US/docs/Web/Guide/HTML/Forms/Sending_and_retrieving_form_data) –