以开发报表软件FineReport为例,在给报表服务器发送请求之前,对URL或者只对URL里面的参数名字和参数值,进行cjkEncode的编码,该方式兼容了各种不同的字符集,如ISO8859-1、 UTF-8、 GBK、 ENU_JP,尤其对中日韩文的处理采取了统一的方案。
1、方法思路使用js数组自带的filter()方法;数据格式要求,父子节点通过,Id,ParentId进行关联。默认父结节id为0。
样例数据:var jsonData = [{"id":"1","pid":"0","name":"家用电器"}, {"id":"4","pid":"1","name":"大家电"}, {"id":"5","pid":"1","name":"生活电器"}, {"id":"2","pid":"0","name":"服饰"}, {"id":"3","pid":"0","name":"化妆"}, {"id":"7","pid":"4","name":"空调"}, {"id":"8","pid":"4","name":"冰箱"}, {"id":"9","pid":"4","name":"洗衣机"}, {"id":"10","pid":"4","name":"热水器"}, {"id":"11","pid":"3","name":"面部护理"}, {"id":"12","pid":"3","name":"口腔护理"}, {"id":"13","pid":"2","name":"男装"}, {"id":"14","pid":"2","name":"女装"}, {"id":"15","pid":"7","name":"海尔空调"}, {"id":"16","pid":"7","name":"美的空调"}, {"id":"19","pid":"5","name":"加湿器"}, {"id":"20","pid":"5","name":"电熨斗"}]
2、实现方法:
function creatTreeData(list){
var clonelist = JSON.parse(JSON.stringify(list))
var result =clonelist.filter(function(father){
var childlist = clonelist.filter(function(child){
return father.id= child.pid
})
if(childlist.length>0){
father.children=childlist
}
return father.pid ==0
})
return result
}
3、方法封装
function treeData(list,id,pid,children){
var clone = JSON.parse(JSON.stringify(list))
return clone.filter(function(father){
var childlist =clone.filter(function(child){
return father[id]==child[pid]
})
if(childlist.length>0){
father[children]=childlist
}
return father[pid]==0
})
}
一楼说的是错的。返回的是字符串,js引擎是不可能直接解析的,直接赋值的操作得到的是个字符串,而不是js Object。需要使用json parse操作,将JSON格式字符串转换成JS对象。
可以使用jQuery(1.4.2+版本)的解析工具 jQuery.parseJSON()工具,或者IE8+以上版本使用浏览器原生的JSON.parse()。如果是IE8以下版本,可以使用json2.js库