grails通过Ajax实现select标签的级联
在grails通过选择select不同的option,通过Ajax查询数据库中的值,返回Json类型的结果,实现页面标签的无刷新级联。1.页面代码,在id为type.id不同的选择返回不同的值到id为brand的select中。
<tr> <td valign="top" class="name"> <label for="type">设备类型</label> </td> <td><select id="type.id" name="type.id" onchange ="setPinPai(this.options.value)"><g:each in="${purCategoryList}"status="i"var="purCategoryIn"> <option value="${purCategoryIn.id}">${purCategoryIn.name}</option> </g:each> </select><font color = "red">*</font> </td> </tr> <tr class="prop"> <td valign="top" class="name"> <label for="brand">设备品牌:</label> </td> <td> <select id ="brand" name="brand"> <g:each in="${brandList}" status="i" var="brand"> <option value="${brand.name}">${brand.name}</option> </g:each> </select><font color = "red">*</font>
2.js进行处理,导入prototype类库,发送Ajax异步请求,获得返回的json类型的值,然后加入到id为brand的select中。
<g:javascript library="prototype" /> <script language="JavaScript" type="text/javascript"> function setPinPai(xiaolei){ var baseUrl = "${createLink(controller:'purList', action:'getJson')}" var url = baseUrl + "?bigId=" +(xiaolei) new Ajax.Request(url, { method: 'get', asynchronous: true, onSuccess:function(req) {update(req.responseText, 'pinpaiMess')} }) } function update(json, mess){ //alert(json); var cjxx = eval( "(" + json + ")" ) //删除所有的值 document.getElementById("brand").options.length=0; for(var i = 0;i<cjxx.length;i++){ var pinPaiText = cjxx.name; var pinPaiValue = cjxx.name; document.getElementById("brand").options.add(new Option(pinPaiText,pinPaiValue)); } } </script>
3.controllor中的处理,通过传入的id好进入数据库进行查询,然后返回json结果。
def getJson ={//处理已经遗留的数据库// println params.id+" getJson""// Sql sql = new Sql(dataSource)// def com_id = params.id// def xiaoleiStr = " select p.name as xiaolei,p.pur_big_cate_id as xiaoleiid from pur_category p "// if(com_id!=null&&com_id!="-1"){// xiaoleiStr =xiaoleiStr+"where p.id = "+com_id// } def com_id = params.bigId println com_id def BrandArray = Brand.findAllByPurCategory(PurCategory.get(com_id)) //def PurCategoryArray = PurCategory.findAllByPurBigCate(PurBigCate.get(com_id)) // println BrandArray.size() render BrandArray as JSON }
页:
[1]