#for product edit page category ajax usage
def all
def recursion(c)
(0..c.children.size-1).each do |j|
cc=c.children[j]
$str+='"'+cc.name+'":{'
if cc.children.size==0
#level+=1
$str+="\"\":#{cc.id}}"
else
recursion(cc)
end
if j!=(c.children.size-1)
$str+=","
else
$str+="}"
end
end
end
$str="{"
$level=1
$left=1
$right=0
top=Category.top
(0..top.size-1).each do |i|
c=top[i]
$str+='"'+c.name+'":{'
if c.children.size==0
#level+=1
$str+="\"\":#{c.id}}"
else
recursion(c)
end
if i!=(top.size-1)
$str+=","
else
$str+="}"
end
end
puts $str
respond_to do |format|
format.html { render :text=>$str}
#format.js { render :json => @options }
#format.xml { render :xml => @categories }
end
end
该方法生成
{"办公":{"文具":{"":13},"电脑周边":{"U盘":{"":15},"鼠标/键盘":{"":16}}},"休闲":{"":11},"潮流":{"":12}}
这样的数据,为了配合http://code.google.com/p/jquery-option-tree/
进行显示
客户端例子
<h2>Example 1</h2>
<input type="text" name="demo1" />
<script type="text/javascript">
$(function() {
var option_tree = {
"Option 1": {"Suboption":200},
"Option 2": {"Suboption 2": {"Subsub 1":201, "Subsub 2":202},
"Suboption 3": {"Subsub 3":203, "Subsub 4":204, "Subsub 5":205}
}
};
option_tree={"办公":{"文具":{"":13},"电脑周边":{"U盘":{"":15},"鼠标/键盘":{"":16}}},"休闲":{"":11},"潮流":{"":12}}
var options = {
empty_value: 'null',
//indexed: true, // the data in tree is indexed by values (ids), not by labels
preselect: {'demo1': ['办公']} // array of default values - if on any level option value will be in this list, it will be selected
// be careful of variable types - '111' !== 111
};
$('input[name=demo1]').optionTree(option_tree,options);
});
</script>
<code><pre>
<input type="text" name="demo1" />
var option_tree = {
"Option 1": {"Suboption":200},
"Option 2": {"Suboption 2": {"Subsub 1":201, "Subsub 2":202},
"Suboption 3": {"Subsub 3":203, "Subsub 4":204, "Subsub 5":205}
}
};
$('input[name=demo1]').optionTree(option_tree);
</pre></code>
最后我们要使用example的例子,使用ajax进行连动,这样就不用递归构造一个完整的json tree了,以上的东西就没用了,花了一个半上午,
递归和递归转非递归忘记了,是慢慢调出来了,不过,其实第一遍就差不多写对了,好像是自己没看清楚{}}对
这个可以做为一道考题来做