捕获HTML下拉值

时间:2014-02-06 10:27:31

标签: python python-2.7 web bottle

我正在学习使用bottle来创建Web应用程序。我是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 个答案:

答案 0 :(得分: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。