2014-02-06 36 views
0

我正在學習使用瓶子來創建Web應用程序。我是HTML新手。捕獲HTML下拉值

如何捕獲下拉值?在一個簡單的例子中,我要求用戶輸入他想記錄多少人的年齡。這看起來如下:

import bottle as bt 
@bt.route('/persons', method = 'GET') 
def count_persons(): 
    return ''' 
     <h3>We are going to collect data on the ages of a number of people</h3> 
     <p>Use the drop down box below to select the number of people who's age you would like to record.</p> 
     <p> 
     <select id="persons"> 
     <option value="2">2</option> 
     <option value="3">3</option> 
     <option value="4">4</option> 
     <option value="5">5</option> 
     </select, name = "persons"> 
     <br/> 
     <input type="submit" name="continue" value="continue"> 
    ''' 

@bt.route('/persons', method = 'POST') 
def render_template(): 
    persons = bt.request.GET.get('persons', '') 
    return 'You have chosen ' + str(persons) 

bt.run(host = 'localhost', port = 8080, debug = True) 

我也試過bt.request.forms('persons')。在我看來,選擇的值應該可以通過下拉菜單的id訪問。這是不對的?

回答

1

您必須使用html表單才能將數據發送到服務器。

import bottle as bt 
@bt.route('/persons', method = 'GET') 
def count_persons(): 
    return ''' 
     <form action="/persons" method="post"> 
      <h3>We are going to collect data on the ages of a number of people</h3> 
      <p>Use the drop down box below to select the number of people who's age you would like to record.</p> 
      <p> 
      <select id="persons"> 
      <option value="2">2</option> 
      <option value="3">3</option> 
      <option value="4">4</option> 
      <option value="5">5</option> 
      </select, name = "persons"> 
      <br/> 
      <input type="submit" name="continue" value="continue"> 
     </form> 
    ''' 

@bt.route('/persons', method = 'POST') 
def render_template(): 
    persons = bt.request.POST.get('persons', '') 
    return 'You have chosen ' + str(persons) 

bt.run(host = 'localhost', port = 8080, debug = True) 

單擊提交按鈕將數據發送到服務器,也將導致頁面重新加載。如果你不想重載頁面,你必須使用XmlHttpRequest。

+0

感謝您的回答。說實話我還不完全清楚。根據我捕獲的輸入信息,我將向用戶返回一個保存在.tpl文件中的表單,該表單使用下拉列表中的整數值創建正確的表單。所以我想我不希望它重新加載。在我承諾的例子中,我只想返回一個簡單的字符串作爲實驗。我是否全部錯了?我認爲我從根本上不理解HTTP方法,這是主要問題。 –