关于ajax:第三阶段-Day05-完成商品后台管理

1. 实现商品后盾治理

1.1 表格数据的展示形式

1.1.1 编辑页面

`</script>-->
            <table class="easyui-datagrid" style="width:500px;height:300px" data-options="url:'datagrid_data.json',method:'get',fitColumns:true,singleSelect:true,pagination:true">
                <thead> 
                    <tr> 
                        <th data-options="field:'code',width:100">Code</th> 
                        <th data-options="field:'name',width:100">Name</th> 
                        <th data-options="field:'price',width:100,align:'right'">Price</th>
                    </tr> 
                </thead> 
            </table>` 

1.1.2 返回值类型的阐明

属性信息: total/rows/属性元素

`{
    "total":2000,
    "rows":[
        {"code":"A","name":"果汁","price":"20"},
        {"code":"B","name":"汉堡","price":"30"},
        {"code":"C","name":"鸡柳","price":"40"},
        {"code":"D","name":"可乐","price":"50"},
        {"code":"E","name":"薯条","price":"10"},
        {"code":"F","name":"麦旋风","price":"20"},
        {"code":"G","name":"套餐","price":"100"}
    ]
}` 

1.2 JSON常识回顾

1.2.1 JSON介绍

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格局。它使得人们很容易的进行浏览和编写。

1.2.2 Object对象类型

1.2.3 Array格局

1.2.4 嵌套格局


例子:

 `{"id":"100","hobbys":["玩游戏","敲代码","看动漫"],"person":{"age":"19","sex":["男","女","其余"]}}` 



1.3 编辑EasyUITablle的VO对象

`package com.jt.vo;

import com.jt.pojo.Item;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.List;
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class EasyUITable {

    private Long total;
    private List<Item> rows;
}` 


1.4 商品列表展示

1.4.1 页面剖析

业务阐明: 当用户点击列表按钮时.以跳转到item-list.jsp页面中.会解析其中的EasyUI表格数据.发动申请url:’/item/query’
要求返回值必须满足特定的JSON构造,所以采纳EasyUITable办法进行数据返回.

`<table class="easyui-datagrid" id="itemList" title="商品列表" 
       data-options="singleSelect:false,fitColumns:true,collapsible:true,pagination:true,url:'/item/query',method:'get',pageSize:20,toolbar:toolbar">
    <thead>
        <tr>
            <th data-options="field:'ck',checkbox:true"></th>
            <th data-options="field:'id',width:60">商品ID</th>
            <th data-options="field:'title',width:200">商品题目</th>
            <th data-options="field:'cid',width:100,align:'center',formatter:KindEditorUtil.findItemCatName">叶子类目</th>
            <th data-options="field:'sellPoint',width:100">卖点</th>
            <th data-options="field:'price',width:70,align:'right',formatter:KindEditorUtil.formatPrice">价格</th>
            <th data-options="field:'num',width:70,align:'right'">库存数量</th>
            <th data-options="field:'barcode',width:100">条形码</th>
            <th data-options="field:'status',width:60,align:'center',formatter:KindEditorUtil.formatItemStatus">状态</th>
            <th data-options="field:'created',width:130,align:'center',formatter:KindEditorUtil.formatDateTime">创立日期</th>
            <th data-options="field:'updated',width:130,align:'center',formatter:KindEditorUtil.formatDateTime">更新日期</th>
        </tr>
    </thead>
</table>` 

1.4.2 申请门路的阐明

申请门路: /item/query
参数: page=1 以后分页的页数.
rows = 20 当前锋分页行数.
当应用分页操作时,那么会主动的拼接2个参数.进行分页查问.

1.4.3 编辑ItemController

`package com.jt.controller;

import com.jt.vo.EasyUITable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jt.service.ItemService;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController //因为ajax调用 采纳JSON串返回
@RequestMapping("/item")
public class ItemController {
    
    @Autowired
    private ItemService itemService;

    /**
     * url: http://localhost:8091/item/query?page=1&rows=20
     * 申请参数:  page=1&rows=20
     * 返回值后果: EasyUITable
     */
    @RequestMapping("/query")
    public EasyUITable findItemByPage(Integer page,Integer rows){

        return itemService.findItemByPage(page,rows);
    }

}` 


1.4.4 编辑ItemService

`package com.jt.service;

import com.jt.pojo.Item;
import com.jt.vo.EasyUITable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jt.mapper.ItemMapper;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {
    
    @Autowired
    private ItemMapper itemMapper;

    /**
     * 分页查问商品信息
     * Sql语句: 每页20条
     *         select * from tb_item limit 起始地位,查问的行数
     * 查问第一页
     *        select * from tb_item limit 0,20;     [0-19]
     * 查问第二页
     *         select * from tb_item limit 20,20;    [20,39]
     * 查问第三页
     *          select * from tb_item limit 40,20;    [40,59]
     * 查问第N页
     *         select * from tb_item limit (n-1)*rows,rows;
     *
     *
     * @param rows
     * @return
     */
    @Override
    public EasyUITable findItemByPage(Integer page, Integer rows) {
        //1.手动实现分页操作
        int startIndex = (page-1) * rows;
        //2.数据库记录
        List<Item> itemList = itemMapper.findItemByPage(startIndex,rows);
        //3.查询数据库总记录数
        Long total = Long.valueOf(itemMapper.selectCount(null));
        //4.将数据库记录 封装为VO对象
        return new EasyUITable(total,itemList);

        //MP
    }
}` 


1.4.5 页面成果展示

1.5 参数格式化阐明

1.5.1 商品价格格式化阐明

1).页面属性阐明
当数据在进行展示时,会通过formatter关键字之后进行数据格式化调用. 具体的函数KindEditorUtil.formatPrice函数.

`<th data-options="field:'price',width:70,align:'right',formatter:KindEditorUtil.formatPrice">价格</th>` 


2).页面JS剖析

`// 格式化价格  val="数据库记录"  展示的应该是放大100倍的数据
    formatPrice : function(val,row){
        return (val/100).toFixed(2);
    },` 

1.5.2 格式化状态信息

1). 页面标识

`<th data-options="field:'status',width:60,align:'center',formatter:KindEditorUtil.formatItemStatus">状态</th>` 


2).页面JS剖析

`// 格式化商品的状态
    formatItemStatus : function formatStatus(val,row){
        if (val == 1){
            return '<span >失常</span>';
        } else if(val == 2){
            return '<span >下架</span>';
        } else {
            return '未知';
        }
    },` 

1.6 格式化叶子类目

1.6.1 页面剖析

阐明:依据页面标识, 要在列表页面中展示的是商品的分类信息. 后端数据库只传递了cid的编号.咱们应该展示的是商品分类的名称.不便用户应用…

`<th data-options="field:'cid',width:100,align:'center',formatter:KindEditorUtil.findItemCatName">叶子类目</th>` 



1.6.2 页面js剖析

 `//格式化名称  val=cid  返回商品分类名称
    findItemCatName : function(val,row){
        var name;
        $.ajax({
            type:"get",
            url:"/item/cat/queryItemName",  //
            data:{itemCatId:val},
            cache:true,    //缓存
            async:false,    //示意同步   默认的是异步的true
            dataType:"text",//示意返回值参数类型
            success:function(data){
                name = data;
            }
        });
        return name;
    }` 

1.6.3 编辑ItemCatPOJO对象

`package com.jt.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.experimental.Accessors;

@TableName("tb_item_cat")
@Data
@Accessors(chain = true)
public class ItemCat extends BasePojo{
    @TableId(type = IdType.AUTO)
    private Long id;
    private Long parentId;
    private String name;
    private Integer status;
    private Integer sortOrder;
    private Boolean isParent;  //数据库进行转化

}` 



1.6.4 编辑ItemCatController

`@RestController
@RequestMapping("/item/cat")
public class ItemCatController {

    @Autowired
    private ItemCatService itemCatService;

    /**
     * url地址:/item/cat/queryItemName
     * 参数: {itemCatId:val}
     * 返回值: 商品分类名称
     */
    @RequestMapping("/queryItemName")
    public String findItemCatNameById(Long itemCatId){

        //依据商品分类Id查问商品分类对象
        ItemCat itemCat = itemCatService.findItemCatById(itemCatId);
        return itemCat.getName();   //返回商品分类的名称
    }

}` 

1.6.5 编辑ItemCatService

`package com.jt.service;

import com.jt.mapper.ItemCatMapper;
import com.jt.pojo.ItemCat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ItemCatServiceImpl implements ItemCatService{

    @Autowired
    private ItemCatMapper itemCatMapper;

    @Override
    public ItemCat findItemCatById(Long itemCatId) {

        return itemCatMapper.selectById(itemCatId);
    }
}` 

1.6.6 页面成果展示

1.7 对于Ajax嵌套问题阐明

1.7.1 问题形容

当将ajax改为异步时,发现用户的申请数据不能失常的响应.

 `//格式化名称  val=cid  返回商品分类名称
    findItemCatName : function(val,row){
        var name;
        $.ajax({
            type:"get",
            url:"/item/cat/queryItemName",
            data:{itemCatId:val},
            //cache:true,    //缓存
            async:true,    //示意同步   默认的是异步的true
            dataType:"text",//示意返回值参数类型
            success:function(data){
                name = data;
            }
        });
        return name;
    },` 

1.7.2 问题剖析

商品的列表中发动2次ajax申请.
1).

`data-options="singleSelect:false,fitColumns:true,collapsible:true,pagination:true,url:'/item/query',method:'get',pageSize:20,toolbar:toolbar">` 



2).ajax申请

1.7.3 解决方案

阐明: 个别条件的下ajax嵌套会将外部的ajax设置为同步的调用.不然可能会犹豫url调用的时间差导致数据展示不齐全的景象.

1.8 对于端口号占用问题


1.9 对于common.js引入问题

阐明:个别会将整个页面的JS通过某个页面进行标识,之后被其余的页面援用即可… 不便当前的JS的切换.

1).引入xxx.jsp页面

2).页面引入JS

1.10 MybatisPlus 实现分页操作

1.10.1 编辑ItemService

`//尝试应用MP的形式进行分页操作
    @Override
    public EasyUITable findItemByPage(Integer page, Integer rows) {
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("updated");
        //临时只封装了2个数据  页数/条数
        IPage<Item> iPage = new Page<>(page, rows);
        //MP 传递了对应的参数,则分页就会在外部实现.返回分页对象
        iPage = itemMapper.selectPage(iPage,queryWrapper);
        //1.获取分页的总记录数
        Long total = iPage.getTotal();
        //2.获取分页的后果
        List<Item> list = iPage.getRecords();
        return new EasyUITable(total, list);
    }` 


1.10.2 编辑配置类

`@Configuration  //标识我是一个配置类
public class MybatisPlusConfig {

    //MP-Mybatis加强工具
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置申请的页面大于最大页后操作, true调回到首页,false 持续申请  默认false
        // paginationInterceptor.setOverflow(false);
        // 设置最大单页限度数量,默认 500 条,-1 不受限制
        // paginationInterceptor.setLimit(500);
        // 开启 count 的 join 优化,只针对局部 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }

}` 

2 商品新增

2.1 工具栏菜单阐明

2.1.1 入门案例介绍

`toolbar: [{          
                  iconCls: 'icon-help',
                  handler: function(){alert("点击工具栏")}      
                  },{
                  iconCls: 'icon-help',          
                  handler: function(){alert('帮忙工具栏')}      
                  },'-',{
                      iconCls: 'icon-save',
                      handler: function(){alert('保留工具栏')}
                  },{
                      iconCls: 'icon-add',
                      text:  "测试",
                      handler: function(){alert('保留工具栏')}
                  }]` 

2.1.2 表格中的图标款式


页面构造:

2.2 页面弹出框成果

2.2.1 页面弹出框成果展示

`$("#btn1").bind("click",function(){

            //留神必须选中某个div之后进行弹出框展示
            $("#win1").window({
                title:"弹出框",
                width:400,
                height:400,
                modal:false   //这是一个模式窗口,只能点击弹出框,不容许点击别处
            })
        })` 


2.3 树形构造展示

2.3.1 商品分类目录构造

阐明:个别电商网站商品分类信息个别是三级目录.
表设计: 个别在展示父子级关系时,个别采纳parent_id的形式展示目录信息.

2.3.2 树形构造入门-html构造

`<script type="text/javascript">
    /*通过js创立树形构造 */
    $(function(){
        $("#tree").tree({
            url:"tree.json",        //加载近程JSON数据
            method:"get",            //申请形式  get
            animate:false,            //示意显示折叠端口动画成果
            checkbox:true,            //表述复选框
            lines:false,                //示意显示连接线
            dnd:true,                //是否拖拽
            onClick:function(node){    //增加点击事件
                
                //控制台
                console.info(node);
            }
        });
    })
</script>` 

2.3.3 树形构造入门-JSON串构造

一级树形构造的标识.
“[{“id”:“3”,“text”:“吃鸡游戏”,“state”:“open/closed”},{“id”:“3”,“text”:“吃鸡游戏”,“state”:“open/closed”}]”

2.3.4 VO对象封装-EasyUITree

`package com.jt.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class EasyUITree implements Serializable {

    private Long id;        //节点ID信息
    private String text;    //节点的名称
    private String state;   //节点的状态   open 关上  closed 敞开
}` 

2.4 商品分类展示

2.4.1 页面剖析

 `<tr>
                <td>商品类目:</td>
                <td>
                    <a href="javascript:void(0)" class="easyui-linkbutton selectItemCat">抉择类目</a>
                    <input type="hidden" name="cid" style="width: 280px;"></input>
                </td>
            </tr>` 


2.4.2 页面JS标识


页面URL标识:

2.4.3 编辑ItemCatController

 `/**
     * 业务需要: 用户通过ajax申请,动静获取树形构造的数据.
     * url:  http://localhost:8091/item/cat/list
     * 参数: 只查问一级商品分类信息   parentId = 0
     * 返回值后果:  List<EasyUITree>
     */
    @RequestMapping("/list")
    public List<EasyUITree> findItemCatList(){

        Long parentId = 0L;
        return itemCatService.findItemCatList(parentId);
    }` 

2.4.4 编辑ItemCatService

`/**
     * 返回值:  List<EasyUITree> 汇合信息
     * 数据库查问返回值:  List<ItemCat>
     * 数据类型必须手动的转化
     * @param parentId
     * @return
     */
    @Override
    public List<EasyUITree> findItemCatList(Long parentId) {
        //1.查询数据库记录
        QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        List<ItemCat> catList = itemCatMapper.selectList(queryWrapper);

        //2.须要将catList汇合转化为voList  一个一个转化
        List<EasyUITree> treeList = new ArrayList<>();
        for(ItemCat itemCat :catList){
            Long id = itemCat.getId();
            String name = itemCat.getName();
            //如果是父级 应该closed   如果不是父级 应该open
            String state = itemCat.getIsParent()?"closed":"open";
            EasyUITree tree = new EasyUITree(id, name, state);
            treeList.add(tree);
        }
        return treeList;
    }` 


2.4.5 页面成果展示

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理