加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

分类——ajax异步实现分类

发布时间:2020-12-16 03:18:19 所属栏目:百科 来源:网络整理
导读:其实就是写api 这里以二级分类为例子:基于TP5 点击省份,就可以获取到城市。 创建api模块创建控制器,创建city.php, ?phpnamespace appapicontroller;use thinkController;use thinkException;class City extends Controller{ private $obj; public fun

其实就是写api

这里以二级分类为例子:基于TP5

点击省份,就可以获取到城市。

创建api模块创建控制器,创建city.php,

<?php
namespace appapicontroller;
use thinkController;
use thinkException;

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 appcommonmodel;


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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读