handlebars结合分页插件实现多条件查询

 
 http://www.jq22.com分页插件结合http://libs.baidu.com/jquery/1.10.2/jquery.min.js。
首先我要吐槽一下这个分页插件有点坑,让我遇到好多问题,这样也好,继el表达式结合jspl实现了用户多条件查询后,我有学回了用handbars加载用户列表。用handle bars加载列表你的 后台必须返回一个json或者json字符串
1 json如下
{
	z:1,
	x:2
}
2 字符串如下
"{
	z:1,
	x:2

}"
详情可到http://json.cn/进行书写验证。如果后台返回的json,前台可以直接调用后台返回来的值,如果前台返回来的是字符串就要在前段加上
userdata=json.Parse(data)调用userdata.handlebars只能加载列表,它加载列表是用ajax请求,这样实现后前后端的分离
,这样分页的时候,每发一次请求,刷新的只有列表,而不是整个页面都刷新。暂且不谈列表字段的格式转换。
	第一步,我们来实现加载列表,将要显示的列表放在TABLE的tbody里面,给TOBODY一个id,把要显示的列表的什么TR,用一个js拿出来。
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/jquery.pagination.css"/>
<script type="text/javascript" src="${pageContext.request.contextPath}/Js/jquery-1.js"></script>

<%--<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>--%>

<script src="${pageContext.request.contextPath}/Js/jquery.pagination.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/Js/handlebars-v4.0.2.js"></script>
<script id="user_table" type="text/x-handlebars-template">
    {{#each usersList}}
    <tr bgcolor="#FFFFFF" id="userDateFor">
        <td height="22" align="center">
            {{jobId}}
        </td>
       <td height="22" align="center">
            {{username}}
        </td>
        <td height="22" align="center">
            {{name}}
        </td>
        <td height="22" align="center">
            {{sex}}
        </td>
        <td height="22" align="center">
            {{birthday}}
        </td>
        <td height="22" align="center">
        {{createtime}}
         </td>
        <td height="22" align="center">
            {{positionId}}
        </td>
        <td height="22" align="center">
            {{content}}
        </td>
        <td height="22" align="center">
            <a href="detailuserView.do?action=deleteUserView&id={{id}}">详情</a>
            <a href="modifyuser.do?action=modifyUser&id={{id}}">修改</a>
            <a href="deleteuser.do?action=deleteUser&id={{id}}">删除</a>
            <input type='checkbox' name='isSelect'value='{{u.id}}'/>
        </td>
    </tr>
    {{/each}}
</script>
注意这段js不要放在tbody里面,里面套用的handbars的标签请百度哦。
  function initTemplate(data) {
                            console.log(data.data);
                            //注册一个Handlebars模版,通过id找到某一个模版,获取模版的html框架
                            //$("#table-template").html()是jquery的语法,不懂的童鞋请恶补。。。
                            var myTemplate = Handlebars.compile($("#user_table").html());

                            //将json对象用刚刚注册的Handlebars模版封装,得到最终的html,插入到基础table中。
                            $('#usersTable').html(myTemplate(data.data));
                        }
上面这个是第一个是js的id,第二个是tobody的Id,用来加载模板

	第二步 开始分页
 <div class="box">
                <div id="pagination1" class="page fl"></div>
                <div class="info fl">
                    <p>当前页数:<span id="current1" class="currentpage">1</span></p>
                </div>
            </div>
上面是分页标签
<script>
			$(function() {
				$("#pagination1").pagination({
					currentPage: 1,
					totalPage: 12,
					callback: function(current) {
						$("#current1").text(current)
					}
				});

			
			});
		</script>
上面试示例分页js代码

刚开始我把我除了搜索的代码全部写到页面初始化加载的方法里面了,这样导致我的代码结构不易理解,自己都搞混。分为五个函数,一个 初始化函数,一个加载列表的函数,还有一个分页函数,一个搜索函数,还有一个加载模板的函数
分页的函数如下
 function initPage(total){
                                $("#pagination1").pagination({
                                    currentPage: 1,
                                totalPage:total,
                                callback: function (current) {
                                    pNum = current;
                                    $("#current1").text(current);
                                   initUserList(pNum);
                                }

                            });
加载列表的函数,注意加载列表的函数里面的参数不能和分页里面的pNum重复,不然会出现互相调用的混乱现象,分页的时候每点击一个页码都会发出多次AJAX请求
    function initUserList(pageNum){
                            var total1;
                            var btn;
                            var drop;
                            var start ;
                            var end;
                            btn = $('#nameIn').val();
                            drop = $('input:radio:checked').val();
                            start = $('#startTime').val();
                            end = $('#endTime').val();
                            $.ajax({
                                type: 'POST',
                                cache: false,
                                async : false,
                                url: '${pageContext.request.contextPath}/users/listUser',
                                //contentType: "application/json; charset=utf-8",
                                data: {"pageNum":pageNum , "pageSize": psize,"sort":drop,"startTime":start,"endTime":end,"username":btn},
                               // data: {"pageNum":pageNum , "pageSize": psize},

                                success: function (data) {

                                    total1 = (Math.ceil(Math.ceil(data.data.count) % Math.ceil(psize))) == 0 ?((Math.ceil(Math.ceil(data.data.count) / Math.ceil(psize)))):((Math.ceil(Math.ceil(data.data.count) / Math.ceil(psize))))+1;
                                    initTemplate(data);

                                }

                            });

                            return total1;
                        }
加载列表的函数是已经带了多条件后的函数了,将加载列表发送请求成功后,返回一个总页数就可以共分页函数调用,这就解决了在分页函数的总页数不知道从哪里得到的问题了。
以前的界面的第一个查询体条件是一个下拉列表框,不管你怎样都会传递给后台一个值,而我后台的mybaties语句是
<select id="selectAllUser"  resultMap="users"  parameterType="map">
        select id,username,name,password,sex,birthday,createtime,
        CASE  WHEN (length(content) <=5) THEN content ELSE CONCAT(left(content,5),'……') END
       as content from users where 1=1
        <trim>
        <if test="username != null" >
          and username like concat(concat('%',#{username}),'%')
        </if>
            <if test="sort ==1 and starTime != null">
                and createtime > #{starTime}
            </if>
            <if test="sort ==1 and endTime != null">
                and createtime < #{endTime}
            </if>
            <if test="sort ==2 and starTime != null">
                and birthday > #{starTime}
            </if>
            <if test="sort ==2 and endTime != null">
                and birthday < #{endTime}
            </if>
            <if test="pageSize != null and pageNum != null">
                limit #{pageNum} ,#{pageSize}
            </if>

        </trim>
    </select>
注意IF语句里面不能打“,”号,但是如果是里面的条件与想下面这样就要打“,”。
<update id="updateSelective" parameterType="com.jointem.hrm.entity.Institution" >
		update rap
		<set >
			<if test="userid != null" >
				userid = #{userid,jdbcType=INTEGER},
			</if>
			<if test="type != null" >
				type = #{type,jdbcType=VARCHAR},
			</if>
			<if test="createtime != null" >
				createtime = #{createtime,jdbcType=DATE},
			</if>
			<if test="content != null" >
				content = #{content,jdbcType=LONGVARCHAR},
			</if>
		</set>
		where id = #{id,jdbcType=INTEGER}
	</update>


 <select id="selectAllCount"  resultType="int"  parameterType="map">
        select count(*) from users where 1=1
        <trim>
            <if test="username != null" >
                and username like concat(concat('%',#{username}),'%')
            </if>
            <if test="sort ==1 and starTime != null">
                and createtime > #{starTime}
            </if>
            <if test="sort ==1 and endTime != null">
                and createtime < #{endTime}
            </if>
            <if test="sort ==2 and starTime != null">
                and birthday > #{starTime}
            </if>
            <if test="sort ==2 and endTime != null">
                and birthday < #{endTime}
            </if>
        </trim>
    </select>

注意我查经过条件查询后所得到的记录数时不能带着分页的条件走。不然查出来的数就只是当前页里面查到的数量,就会少了很多。
也就是说即使我开始时间后结束时间没有值传到后台,只要我下拉列表有值,都会走查询的的条件部分,传了sort,但又没有是时间值,所以就不能查询到值,于是我把下拉列表改成单选按钮,只要两个按钮的name一致就行。其实我的sql写的不是很严谨,查询到的值不是位于开始时间后结束时间之间
本人对这个mybaties不是很熟悉。
  function lookup() {
                            var totalPage = initUserList(1);
                            //  alert(totalPage);
                            initPage(totalPage);

                        }
这个就是我的搜索调用函数
到这里我的界面函数就差不多了,可是我们发现这个时期类型,中文类型,性别显示不正常。我们要把他该为寻常见到的那样。
在前段转化格式太复杂,要年月日都要转化,我们在后端的json类里面写一个方法
 public String toJson() {
        // 处理NUll
        // return JSONUtil.createJsonString(this);
        // return JSON.toJSONString(this,SerializerFeature.WriteMapNullValue);
        return JSON.toJSONString(this, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat);
    }
里面加入了writeMapNullValue,当我们put进去的value是空值的时候,不加这个查看控制台的显示,map里面就不会显示这个put的值,加上这个就会显示这个put进去的值是空,还加了一个时间转化的
WriteDateUseDateFormat,全局修改日期格式。这样就不会显示看不懂的时间格式了。运行项目,发现有些中文字段是?号。查看数据库,数据库显示正常。在control类里面的显示列表方法打个断点,看


图中可以看到map里面的中文是正常显示的,于是我们加入请求的编码格式
@RequestMapping(value = "/listUser",method=RequestMethod.POST,produces = "application/json;charset=utf-8")
大功告成
后台方法
 @RequestMapping(value = "/listUser",method=RequestMethod.POST,produces = "application/json;charset=utf-8")
    @ResponseBody
    public String toListUser(HttpServletRequest req) {
        String sort = req.getParameter("sort");
        String startTime = req.getParameter("startTime");
        String endTime = req.getParameter("endTime");
        String username = req.getParameter("username");
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");

        JsonResult jsonResult = new JsonResult();
        Map<String, Object> resMap = new HashMap<String, Object>();
        List<Users> list = userService.selectUsers(sort, startTime, endTime, username, pageNum, pageSize);
        int count = userService.selectAllCount(sort, startTime, endTime, username);
        resMap.put("usersList", list);
        resMap.put("count", count);
        jsonResult.setData(resMap);
        jsonResult.setCode("0000000");
        jsonResult.setMsg("success");
        return jsonResult.toJson();
    }

前端的全局变量
  var psize = 5;
                            var pNum ;

                             Handlebars.registerHelper('createtime', function() {
                             return this.createtime.substring(0, 10);
                             });
                            Handlebars.registerHelper('birthday', function() {
                                return this.birthday.substring(0, 10);
                            });
                            Handlebars.registerHelper('sex', function() {
                                if(this.sex == 1){
                                    return "男";
                                }else{
                                    return "女";
                                }
                            });
以上分页有点问题,我如果加入条件查询后的列表是对的,但是分页的总页数还是不带条件查询的总页数。这是因为,与后台多次交互的总页数没有传递到handlebars列表加载函数里面



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值