我正在尝试使用我在这里找到的 ajax 搜索切片:http://www.web2pyslices.com/slices/take_slice/51
但由于某种原因,我不断收到错误:
IndexError: list index out of range
这是我的代码版本:
default.py( Controller )
def index():
listings = db().select(db.listing.ALL, orderby=db.listing.first_name)
return dict(listings=listings, livesearch=livesearch())
def livesearch():
partialstr = request.vars.values()[0]
query = db.listing.title.like('%'+partialstr+'%')
listings = db(query).select(db.listing.title)
items = []
for (i,listing) in enumerate(listings):
items.append(DIV(A(listing.title, _id="res%s"%i, _href="#", _onclick="copyToBox($('#res%s').html())"%i), _id="resultLiveSearch"))
return TAG[''](*items)
livesearch.html( View ,我在layout.html中{{include}}
<input type="text" id="search" name="search" autocomplete="off" onkeyup="getData(this.value);" /><br />
<div id="ajaxresults"></div>
db.py(模型)
db.define_table(auth.settings.table_user_name,
Field('first_name'),
Field('last_name'),
Field('email'),
Field('password','password', length=512, readable=False, label='Password'),
Field('title'),
Field('photo','upload'),
Field('bio','text'),
Field('phone'), # Contact details
Field('website'),
Field('address'),
Field('registration_key', length=512,
writable=False, readable=False, default=''),
Field('reset_password_key', length=512,
writable=False, readable=False, default=''),
Field('registration_id', length=512,
writable=False, readable=False, default=''),
)
listing = db[auth.settings.table_user_name]
任何帮助将非常非常感谢,因为我已经绞尽脑汁好几天了(因为我对编程非常陌生)
谢谢!
最佳答案
def index():
listings = db().select(db.listing.ALL, orderby=db.listing.first_name)
return dict(listings=listings, livesearch=livesearch())
您不想从 index
函数返回 livesearch
。根据slice您引用的,应通过 Ajax 从您的 index
页面调用 livesearch
函数。
def livesearch():
partialstr = request.vars.values()[0]
我知道上面的行是直接从切片中获取的,但是访问发布变量的值的更好(也是更典型的方式)是:
partialstr = request.vars.partialstr if request.vars else None
注意,如果没有 request.vars
或 request.vars.partialstr
不存在,上述语法将返回 None
,因此不会产生错误。
此外,只要没有请求变量,request.vars
将为 None
,因此您始终可以使用以下方法测试请求变量:
if request.vars:
最后,您可能对web2py的内置auto-complete widget感兴趣。 (尽管我认为 IE 中可能存在一些问题,修复工作正在进行中)。
关于python - web2py Ajax 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6990860/