网上有很多有javascript实现类似Google自动提示功能,但是用grails的remote标签,就简单多了。
示例涉及code:quizQuestionController,edit.gsp,_searchHulu.gsp
首先controller中写一个异步搜索的方法:
def searchHulu = {
def word = "%${params.value}%"
params.offset = params.offset?params.offset as int:0
def total = HuluVideo.executeQuery("select count(*) from HuluVideo as hv where hv.title like /'${word}/'").get(0)
def olist = HuluVideo.findAllByTitleLike(word,[max:10,offset:params.offset, order:"title"])
//def olist = HuluVideo.executeQuery('from HuluVideo as hv where hv.title like :word order by hv.title',[word:word,offset:params.offset,max:max])
render(template: '/gspTemplate/searchHulu', model: [list: olist,total:total,offset:params.offset])
}
其次,在edit.gsp中涉及的代码如下:
<tr class="prop" >
<td valign="top" class="name">
<label for="hulu">Hulu:</label>
<input id="huluid" name="huluid" type="hidden" value="${quizQuestionInstance?.hulu?.id}"/>
</td>
<td valign="top">
<g:remoteField action="searchHulu" update="titleDiv" name="huluTitle" value="${quizQuestionInstance?.hulu?.title}"></g:remoteField>
<div id="titleDiv">choose</div>
</td>
</tr>
当然head中有个简单的javascript函数实现点击列表时把数据填充到输入框中
<g:javascript library="prototype" />
<script type="text/javascript">
function f(str,id){
document.getElementsByName(id)[0].value = str;
}
</script>
再次,_searchHulu.gsp代码如下:
<%
response.setContentType("text/xml;charset=UTF-8");
%>
<table>
<tr>
<ul>
<g:each in="${list}" var="row" >
<li id="${row?.id}" οnclick="f('${row?.title}','huluTitle');" >${row?.title}</li>
</g:each>
</ul>
</tr>
//分页
<div id="paginate">
<g:if test="${total > offset && offset >= 10}">
<g:remoteLink action="searchHulu" update="titleDiv" params="[value:params.value,offset:(params.offset - 10)]"><<pre</g:remoteLink>
</g:if>
<g:if test="${total > 0}">
<span>${total}</span>
</g:if>
<g:if test="${total > offset+10}">
<g:remoteLink action="searchHulu" update="titleDiv" params="[value:params.value,offset:(params.offset + 10)]">next>></g:remoteLink>
</g:if>
</div>
</table>
实现效果: