web2py Ajax 搜索
我正在尝试在我的网站上使用一个ajax搜索功能,这个功能我在这里找到的:http://www.web2pyslices.com/slices/take_slice/51
但是不知为什么,我总是遇到这个错误:
IndexError: list index out of range
这是我写的代码版本:
default.py(控制器)
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(视图,我在layout.html中{{包含}}的)
<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]
如果能得到任何帮助,我将非常非常感激,因为我已经为这个问题绞尽脑汁好几天了(因为我对编程非常陌生)
谢谢!
2 个回答
如果你的 index() 代码是这样的:
def index():
listings = db().select(db.listing.ALL, orderby=db.listing.first_name)
return dict(listings=listings, livesearch=livesearch())
那么,当你访问 index.html 页面时,livesearch() 函数会被调用,但这时候,request.vars.values() 是空的,所以会出现 IndexError(索引错误)。
不要在 index() 中调用 livesearch(),而是使用 ajax 将搜索词发送到 livesearch.html,这样 web2py 就会调用 livesearch(),这时 request.vars.values()[0] 就是你输入的搜索词。
def index():
listings = db().select(db.listing.ALL, orderby=db.listing.first_name)
return dict(listings=listings, livesearch=livesearch())
你不应该直接从 index
函数返回 livesearch
。根据你提到的 这个链接,livesearch
函数应该通过 Ajax 从你的 index
页面调用。
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 内置的 自动完成组件 感兴趣(不过我觉得在 IE 浏览器上可能会有一些问题,正在修复中)。