适用范围:省市无限级联动,商品类别无限极联动
需要使用到的jQuery插件为cxselect,ok说不清楚,还是直接上代码比较直观
HTML代码如下:
js代码如下:
1 2 3 function checkForm(){ 4 var categorys = []; 5 $("#cate").each(function () { 6 var val = $(this).val(); 7 if (val != "") { 8 categorys.push(val); 9 }10 });11 if (categorys.length == 0) {12 alert("请选择类别。");13 return false;14 }15 return true;16 }17 18 $.cxSelect.defaults.url = '/category/category.json';19 $('#element_id').cxSelect({20 selects: ['select1', 'select2', 'select3', 'select4', 'select5'],21 nodata: 'none',22 required:false,23 firstTitle:'----全部----',24 firstValue:''25 });
category.json文件需要在类别管理中生成所有类别的json文件,php控制器代码如下:
1 /*生成类别json数据*/2 public function createJson(){3 $categoryModel = new CateModel();4 if($categoryModel->wirteJson()){5 echo "";6 }else{7 echo "";8 }9 }
php模型代码如下:
1 /*生成类别JSON数据*/ 2 public function wirteJson(){ 3 $dataInfo = \think\Db::query("select id as v,name as n,pid from think_pro_category"); 4 $data = $this->getCategoryJson($dataInfo); 5 return $data; 6 } 7 8 /** 9 * 功能:无限级类别json数据生成10 * 参数:$data 类别查询结果集11 * 返回值:$json 递归查询排序后的json数据12 */13 public function getCategoryJson($dataInfo) {14 /*生成json数据*/15 foreach($dataInfo as $category) {16 $tree[$category['v']] = $category;17 $tree[$category['v']]['s'] = array();18 }19 $content = json_encode(generateTree($tree));20 $content = str_replace(',"s":[]', "", $content);21 // for( $i = 0; $i < count($dataInfo); $i++ ) {22 // $content = str_replace('"'.$dataInfo[$i]['v'].'":', "", $content);23 // }24 //$content = '['.substr($content,1,strlen($content)-2).']';25 //return $content;26 /*写入文件*/27 //文件存放路径28 $filePath = $_SERVER['DOCUMENT_ROOT'].DS.'/category/category.json';29 $returnval = file_put_contents($filePath,$content);30 // $fopen = fopen($filePath,'w+');31 // fwrite($fopen,$content);32 // fclose($fopen);33 return $returnval;34 }
公共函数:
1 /** 2 *处理分类数组 3 **/ 4 function generateTree($items) { 5 $tree = array(); 6 foreach($items as $item){ 7 if(isset($items[$item['pid']])){ 8 $items[$item['pid']]['s'][] = &$items[$item['v']]; 9 }else{10 $tree[] = &$items[$item['v']];11 }12 }13 return $tree;14 }