如何在Bottle中获取多列表中的所有项目?
我有一个表单,可以用JavaScript往一个多选列表里添加内容。我想把这个列表里的所有数据发送到我的Bottle服务器,但我现在还不知道怎么把这些数据发送过去。请问我该怎么把我列表里的所有项目发送到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>
补充说明:
我想获取整个列表,而不仅仅是选中的值。用户通过文本框、按钮和JavaScript来添加内容,所以我想获取所有的值(或者说所有的新值)。
补充说明2:
我使用了提供的答案和一些JavaScript,达到了我想要的效果:
$('.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 个回答
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>
输出到标准输出的结果看起来是这样的:
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
[]
第一次选择了两个对象,第二次没有选择任何对象。
4
你已经很接近了;试试这个:
all_selected = bottle.request.forms.getall('the_list')
你需要使用 request.forms 和 getall。request.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