如何获取瓶中多列表中的所有项目?

时间:2014-03-22 15:46:51

标签: python bottle

我有一个表单允许我使用js添加到多列表。我希望能够将该列表中的所有数据发布到我的瓶子服务器,但我无法获得任何数据。如何将我的语句中的所有项目发布到server.py?发布后如何访问此帖子数据?

相关代码:

server.py:

@bottle.route('/saveList', method='POST')
def save_list():
    forms = bottle.request.get('the_list')
    print forms # returns 'None'
    return bottle.redirect('/updatelist') # just redirects to the same page with a new list

list.tpl

 <select multiple="multiple" id="the_list" name="the_list">
     %for item in my_ list:
     <option>{{item}}</option>
     %end
 </select>

编辑:

我正在尝试获取整个列表,而不仅仅是选定的值。用户通过textfield,button和JS添加到multi;所以我想获得所有值(或所有新值)。

编辑2:

我使用了提供的答案以及一些js来获得所需的结果:

$('.add_to_the_list').click(function (e) {
...
var new_item = $('<option>', {
                value: new_item_str,
                text: new_item_str,
                class: "new_item" // the money-maker!
            });
...

function selectAllNewItem(selectBoxId) {
    selectBox = document.getElementById(selectBoxId);
    for (var i = 0; i < selectBox.options.length; i++) {
        if (selectBox.options[i].className === "new_item") { // BOOM!
            selectBox.options[i].selected = true;
        }
    }
}

...
    $('#submit_list').click(function (e) {
        selectAllNewBG("the_list")
    });

2 个答案:

答案 0 :(得分:4)

你很亲密;试试这个:

all_selected = bottle.request.forms.getall('the_list')

您需要使用request.formsgetallrequest.forms返回一个MultiDict,它是用于存储多个选定选项的适当数据结构。 getall是从MultiDict中检索值列表的方法:

for choice in all_selected:
    # do something with choice

或更简单地说:

for selected in bottle.request.forms.getall('the_list'):
    # do something with selected

答案 1 :(得分:2)

要获取多个值,请使用.getall。这是我能用它的代码。

import bottle

@bottle.route('/saveList', method='POST')
def save_list():
    forms = bottle.request.POST.getall('the_list')
    print forms 
    return bottle.redirect('/updatelist')

@bottle.route('/updatelist')
@bottle.view('index')
def index():
    return {}

bottle.run()

HTML

<html>
    <body>
        <form method="post" action="http://localhost:8080/saveList">
             <select multiple="multiple" id="the_list" name="the_list">
                 <option value="1">Item 1</option>
                 <option value="2">Item 2</option>
                 <option value="3">Item 3</option>
             </select>
            <input type="submit" />
         </form>
    </body>
</html>

stdout的输出如下:

127.0.0.1 - - [22/Mar/2014 13:36:58] "GET /updatelist HTTP/1.1" 200 366
['1', '2']
127.0.0.1 - - [22/Mar/2014 13:37:00] "POST /saveList HTTP/1.1" 303 0
127.0.0.1 - - [22/Mar/2014 13:37:00] "GET /updatelist HTTP/1.1" 200 366
[]

第一次选择了两个对象,第二次没有选择任何对象。

相关问题