======================================================
注:本文源代码点此下载
======================================================
今儿个老师让用rails实现二级菜单动态无刷新,而且要默认显示原目录选项,这下愁坏啦!还好网上牛人很多,用jquery实现了无刷新二级级联菜单,试了一下,成功!在分享一下下~~
环境:winxp,ruby1.8.7-p352,rails 2.3.14
数据库中:目录表categories,字段 id parentid name,parentid 为0是父级。
新闻表news,字段 id title content category_id,category_id为目录id(表间已关联)
基本思路:在select中嵌入js函数,当选择项改变时触发事件,使用jquery的aja函数调用news_controller中的方法,获取子菜单,并回传给二级select。
首先引入jquery文件
修改controller中edit
# get /news/1/edit
def edit
@new = news.find(params[:id])
@parent = category.find(:all,:conditions=>["parentid = 0"])
@classes = category.find(:all,:conditions=>["parentid = ?",@new.category.parentid])
end
view页面中
false, :selected =>@parenid}),
:onchange => "get_options(this.value)" %>
false, :selected =>@new.category_id} %>
添加js的get_options方法
其中调用了news中的get_child_cate方法,于是在news_controller添加方法
def get_child_cate
options = ""
city = category.find(:all, :conditions => ["parentid = ?", params[:id]])
city.each do |s|
options #{s.name}"
end
render :text => options
end
ok大功告成~!
绿色通道:好文要顶关注我收藏该文与我联系
======================================================
在最后,我邀请大家参加新浪APP,就是新浪免费送大家的一个空间,支持PHP+MySql,免费二级域名,免费域名绑定 这个是我邀请的地址,您通过这个链接注册即为我的好友,并获赠云豆500个,价值5元哦!短网址是http://t.cn/SXOiLh我创建的小站每天访客已经达到2000+了,每天挂广告赚50+元哦,呵呵,饭钱不愁了,\(^o^)/