Grails Ajax 实现 联动选择
如果在jsp中添加<g:javascript library="prototype" />再使用g:remoteLink,g:formRemote等可实现异步刷新。
查看生成的html会发现主要实现代码如下
new Ajax.Updater('Bdiv','/Test/test/b', {asynchronous:true,evalScripts:true});return false;
有了这段语句,可以在JavaScript脚本中方便实现异步刷新,而不会仅仅限制在grails提供的几个Tag。
如,欲实现简单的无刷新关联select
a.gsp
<html><head><title>test</title><g:javascript library="prototype" /><script language="JavaScript">function sel(){ var select = document.getElementById("A"); var index = select.selectedIndex; var a = select.options[index].value; new Ajax.Updater('Bdiv','/Test/test/b?Aid='+a, {asynchronous:true,evalScripts:true});return false; }}</script><body><select id="A" onChange="sel();"><option vaule="1">1</option><option vaule="2">2</option><option vaule="3">3</option></select><div id="Bdiv"></div></body></html>
b.gsp
<select id="B"><g:each in="${BB}" var="bInstance"> <option value="${bInstance.id}">${bInstance.name}</option></g:each></select>
TestController.groovy
class TestController{ def index = { redirect(action:a,params:params) } def a={[params:params]} def b={ render(action:"b",model:[BB:B.findAllByA(params.Aid)]) }}
B.groovy
class B{String nameInteger A}
这样,动了A之后,B会根据A的内容从数据库查询出A值为Aid的所有B,然后列在B选框中。
g:select标签是多选框,单选框标签没有找到,就这样实现了。
联动选择有JavaScript能很简单实现,这儿只是一个Ajax.Updater的一个用法。
初学者,有错误的地方望大家不吝赐教。谢谢!