做个简单的thinkphp三级联动

xiaoxiao2021-02-28  79

上图是个省市县的表。具体数据截图如下。

首先我们在thinkphp里找个controller,我这里是BusinessController.class.php,相应的前台business写个liandong.html页面。

liandong.html代码如下:

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Thinkphp实现Ajax地区的三级联动</title>     <script src="__PUBLIC__/Home/js/jquery.1.7.2.min.js"></script></head><!-- 找到自己的jq文件--> <body> <!-- 省份 -->     <select name="pro" id="pro">         <foreach name="region" item="v">             <option value="{$v.id}">{$v.name}</option>         </foreach>     </select> <!-- 城市 -->     <select name="city" id="city">         <option></option>     </select> <!-- 区县 -->     <select name="area" id="area">         <option></option>     </select>      <script>     $('#pro').change(function(){         $.ajax({             type:"post",             url:"{:U('business/liandong')}",             data:'pro_id='+$('#pro').val(),             dataType:"json",             success:function(data){                 $('#city').html(data);             }         });     });          $('#city').change(function(){         $.ajax({             type:"post",             url:"{:U('business/liandong')}",             data:'pro_id='+$('#city').val(),             dataType:"json",             success:function(data){                 $('#area').html(data);             }         });     }); </script> </body> </html>

BusinessController.class.php里的liandong方法如下:

public function liandong(){         if (IS_POST) {             $parent_id['pid'] = I('post.pro_id','addslashes');             $region = M('city')->where($parent_id)->select();             $opt = '<option>--请选择市区--</option>';             foreach($region as $key=>$val){                 $opt .= "<option value='{$val['id']}'>{$val['name']}</option>";              }              echo json_encode($opt);                          } else {             $parent_id['pid'] = 1;             $region = M('city')->where($parent_id)->select();             $this->assign('region',$region);             $this->display();         }              } 

此文借鉴引用http://www.thinkphp.cn/topic/41905.html

转载请注明原文地址: https://www.6miu.com/read-35219.html

最新回复(0)