[英]web.py Json with Multiple select
我正在使用Web.py框架。我的html页面中有一个动态下拉列表,可以使用jquery和json很好地工作,但是当我添加具有多个属性的select标签时,在web.py中收到一个关键错误。避免这个问题。
编辑 :我在python s = web.input()['text'] KeyError中得到以下错误:'text'
PS:我是Web开发的新手
这是我的json / jquery代码:
<script type="text/javascript" >
jQuery(document).ready(function() {
jQuery("#primaryl").bind('change click', function() {
var pid = $$(this).val();
if (pid != '') {
jQuery.ajax({
type: "PUT",
url: "/getloc",
async: false,
data: {text: pid},
dataType: "json",
success: function(regions) {
$$("#secl").empty();
$$("#secl").append("<option value='0'>SECONDARY</option>");
$$.each(regions, function(index, region) { $$("#secl").append("<option>" + region + "</option>"); });
}
});
} else {
jQuery("#secl").html("Failed");
}
return false;
});
});
HTML代码:
<!--first select-->
<select name="primaryl" id="primaryl" multiple="multiple">
<option value="0">PRIMARY</option>
</select>
<!--second select-->
<select name="secl" id="secl"><option value="0">SECONDARY</option></select>
web.py代码:
class Getloc:
def PUT(self):
s = web.input()['text']
result = db.select('location')
for user in result:
if user.lname == s:
lid = user.lid
result = db.select('location')
sec_dict = []
i = 0
for users in (result):
if users.lparent==lid:
sec_dict.append(users.lname.encode('ascii','ignore'))
i = i + 1;
if i == 0:
sec_dict = ['None']
return json.dumps(sec_dict)
看来问题出在JavaScript / AJAX方面。 web.py代码总是做同样的事情,似乎根本没有任何可能导致任何错误的东西。
最好的选择是使用Firebug或Chrome或Safari的内置开发/调试控制台检查传出的HTTP请求,以查看在两种情况下text
参数是否确实存在。
另外,这是带有注释的Python代码的更合理版本:
import json
import db
import web
class Getloc(object):
def PUT(self):
s = web.input()['text']
# doesn't the DB layer web.py allow you to directly query the rows
# that match your criteria? filtering in your code is inefficient
for user in db.select('location'):
if user.lname == s:
lid = user.lid
break # once found, save CPU time and don't keep iterating
# sec_dict = [] # this is not a dict, it's a list, but it's not
# needed anyway--use list comprehensions instead
# i = 0 # not needed in this case, but if you need iteration with
# indexing, use `for ix, elem in enumerate(elems)`
# same question--can't you just have the DB do the filtering?
ret = [user.lname.encode('ascii', 'ignore')
for user in db.select('location')
if user.lparent == lid]
# if not ret:
# ret = [None] # this is a bad idea; just return an empty list
return json.dumps(ret)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.