分类——ajax异步实现分类

其实就是写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

转载于:https://my.oschina.net/u/3530967/blog/1545732

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值