其实就是写api
这里以二级分类为例子:基于TP5
点击省份,就可以获取到城市。
创建api模块创建控制器,创建city.PHP,
<?PHP namespace app\api\controller; use think\Controller; use think\Exception; class City extends Controller { private $obj; public function _initialize() { $this->obj = model("City"); } /** * 商户入驻通过省找城市 * @return mixed */ public function getCitysByParentId() { $id = input('post.id'); // echo $id;die; if(!$id) { $this->error('ID不合法'); } //halt($id); // 通过id获取二级城市 将父类id传入 $citys = $this->obj->getNormalCitysByParentId($id); if(!$citys) { throw new Exception('资源未找到',404); } return $this->result($citys,200); } }
getNormalCitysByParentId方法
<?PHP /** * Created by PHPStorm. * User: Administrator * Date: 2017/9/25 * Time: 14:46 */ namespace app\common\model; class City extends Base { /* *获取城市分类,获取城市的父类id */ public function getNormalCitysByParentId($parentId=0) { $data = [ 'status' => 1,'parent_id' => $parentId,]; $order = [ 'id' => 'desc',]; return $this->where($data) ->order($order) ->select(); } }
js实现ajax接收PHP api数据
<script type="text/javascript"> /** * 点击城市获取二级城市 */ var SCOPE = { city_url' : '{:url('api/city/getCitysByParentid')}',} $(".cityId").change(function(){ city_id = $(this).val(); url = SCOPE.city_url; postData = {'id':city_id}; // 抛出请求 $.post(url,postData,function(result){ // todo if(result.code == 200){ // 将信息填充到变量 // [{id: 13,name: "吉安",uname: "jian",parent_id: 4,listorder: 0,status: 1,…},…] data = result.data; city_html = ""; $(data).each(function(){ city_html += "<option value='"+this.id+"'>"+this.name+"</option>>"; }); $('.se_city_id').html(city_html); } else { // alert(result.message); $('.se_city_id').html(''); return; } },"json"); }); </script>
可以将主要的js代码分离到公共js