Spring MVC Ajax请求加载更多

配置****-dispatcher-servlet.xml


<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
    <!--
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>  
     -->
    <!-- freemarker模板 -->
     <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
        <property name="templateLoaderPath" value="WEB-INF/ftl/" />  
        <property name="defaultEncoding" value="UTF-8" />  
     </bean>  
     <!-- freemarker视图解析器 -->  
     <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
        <property name="suffix" value=".ftl" />  
        <property name="contentType" value="text/html;charset=UTF-8" />  
        <!-- 此变量值为pageContext.request, 页面使用方法:rc.contextPath -->  
        <property name="requestContextAttribute" value="rc" />  
     </bean> 


Ajax请求返回的数据Model

public class ResponseData {
    public static final int SUCCESS = 200;
    public static final int DEFAULT_ERROR = 500;
    
    public static ResponseData newSuccess(String message) {
        ResponseData rd = new ResponseData(true, null);
        rd.setStatus(SUCCESS);
        rd.setMessage(message);
        
        return rd;
    }
    
    
    public static ResponseData newSuccess(Object data) {
        return ResponseData.newSuccess("", data);
    }
    
    public static ResponseData newSuccess(String message, Object data) {
        ResponseData rd = new ResponseData(true, data);
        rd.setStatus(SUCCESS);
        rd.setMessage(message);
        
        return rd;
    }
    
    public static ResponseData newFailed(String message) {
        ResponseData rd = new ResponseData(false, null);
        rd.message = message;
        rd.setStatus(DEFAULT_ERROR);
        return rd;
    }
    
    public static ResponseData newFailed(Object data) {
        return ResponseData.newFailed("", data);
    }
    
    public static ResponseData newFailed(String message, Object data) {
        ResponseData rd = new ResponseData(false, data);
        rd.message = message;
        rd.setStatus(DEFAULT_ERROR);
        return rd;
    }
    
    private boolean success;
    private Object data;
    private String message;
    private int status;
    
    private List<String> errors;
    private Map<String, String> fieldErrors;
    
    public ResponseData(boolean success, Object data) {
        this.success = success;
        this.data = data;
    }
    
    public boolean isSuccess() {
        return success;
    }
    public void setSuccess(boolean success) {
        this.success = success;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
    public List<String> getErrors() {
        return errors;
    }
    public void setErrors(List<String> errors) {
        this.errors = errors;
    }
    public Map<String, String> getFieldErrors() {
        return fieldErrors;
    }
    public void setFieldErrors(Map<String, String> fieldErrors) {
        this.fieldErrors = fieldErrors;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }    
}

分页公共类

public class Pagination<T> {
    private int currentPage;

    private long total;
    private List<T> rows;
    private int totalPages;
    
    public Pagination() {
        this.total = 0;
        this.totalPages = 0;
        this.rows = Collections.emptyList();
    }
    
    public Pagination(Page<T> page) {
        this.total = page.getTotalElements();
        this.rows = page.getContent();
        this.totalPages = page.getTotalPages();
        this.currentPage = page.getNumber();
    }
    
    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public List<T> getRows() {
        return rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    /**
     * @return the totalPage
     */
    public int getTotalPages() {
        return totalPages;
    }

    /**
     * @param totalPage the totalPage to set
     */
    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }    
}


Controller

/**
 *
 * @author Bruce
 *   
 */
@Controller
public class MyUserAwardController extends AbstractController{
    
    @Autowired
    private MyUserAwardService myUserAwardService;
 

   //首次访问加载

    @RequestMapping(value = "/8888/9999.do")
    public String index(HttpServletRequest request,HttpServletResponse response,
            @RequestParam(value = "page",defaultValue="0") int page,
            @RequestParam(value = "pageSize",defaultValue="30") int rows,Model model){
        Restriction<UserAwardPO> restriction = new Restriction<UserAwardPO>(createPageRequest(page, rows, new Sort(Direction.DESC, "id")));
        
        Pagination<UserAwardPO> results = myUserAwardService.pagingMyUserAward(restriction);

        model.addAttribute("pagination", results);
        
        return "/user/my_user_award_list";
    }
    //JQuery Ajax请求加载  返回ResponseDataModel 需要加入@ResponseBody注解
    @RequestMapping(value = "/8888/9999Ajax.do")
    public @ResponseBody ResponseData malcByUserAjax(@RequestParam(value = "page",defaultValue="0") int page,
            @RequestParam(value = "pageSize",defaultValue="30") int rows,Model model){
        Restriction<UserAwardPO> restriction = new Restriction<UserAwardPO>(createPageRequest(page, rows, new Sort(Direction.DESC, "id")));
        
        Pagination<UserAwardPO> results = myUserAwardService.pagingMyUserAward(restriction);

        model.addAttribute("pagination", results);

        ResponseData responseData = ResponseData.newSuccess("操作成功.", results);
        
        return responseData;
    }

}

公共页面

_default_layout.ftl

<#setting number_format="0.######">
<#macro defaultHeader>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta name="renderer" content="webkit">
    <title>*****${(title??)?string('-' + title!"", '')}</title>
    <meta name="description" content="${(description??)?string(description!"", '')}">    
    <link rel="stylesheet" href="${rc.contextPath}/assets/css/amazeui.min.css?v=ingyazov">
    <script src="${rc.contextPath}/assets/js/jquery.min.js?v=ingyazov"></script>
    <script src="${rc.contextPath}/assets/js/handlebars.min.js?v=ingyazov"></script>
    <script src="${rc.contextPath}/assets/js/amazeui.min.js?v=ingyazov"></script>
    <#list styles as style>
    <link rel="stylesheet" href="${style}">
    </#list>
    <#list javascripts as js>
    <script type="text/javascript" src="${js}"></script>
    </#list>
    <style>
    html,body {-webkit-user-select:none; user-select: none; }
    </style>
</#macro>

<#macro layout header=defaultHeader>
<!DOCTYPE html>
<html class="no-js m">
<head>
<@header />
</head>
<body>
<#nested>
</body>
</html>
</#macro>


my_user_award_list.ftl 页面

<#include "../layout/_default_layout.ftl">
<#assign title="****">
<#assign description="****">
<#assign styles=["${rc.contextPath}/assets/css/client-app.css","${rc.contextPath}/assets/css/sweet-alert.css"]>
<#assign javascripts=["${rc.contextPath}/assets/js/sweet-alert.min.js"]>
<@layout>
<style type="text/css">
.list-award ul {
    display: table;
    width: 100%;
    border-collapse:collapse;
    border-spacing:0px;
}

.list-award li {
    display: table-row;
    width:100%;
    border-bottom: solid 10px #f6f6f6 !important;
    background-color: #FFF;
}

.list-award .cell {
    display: table-cell;
    height: 100%;
    padding: 10px;
    text-align: left;
    vertical-align: top;
}

.cell-logo {
    width:120px;
    height:120px;
}

.cell-logo img {
    width:100px;height:100px;
}

.cell-award {
    position:relative;
}

.cell-score {
    width: 120px;
    position:relative;
    padding-top:20px !important;
    text-align: center;
}

.award-num {
    position:absolute;bottom:10px;right:10px;
}

.score {
    text-align:center;
    font-size: 18px;
    color: red;
}

.list-award .logo {
    margin-top: 10px;
}

.btn-status-un {
    font-size:14px;height:30px;width:100px;
}
</style>

     <div class="tc-list-widget list-award" style="margin-top:10px;">
            <ul id="datalist">
                <#list pagination.rows as i>
                    <li class="tc-list-item" >
                        <div class="cell cell-logo">
                            <div class="logo">
                                <img src="${i.award.picUrl!""}" alt="${i.award.name!""}">
                            </div>
                        </div>
                        <div class="cell cell-award">
                            <div style="margin-top:10px;">
                                <span>${i.award.name!""}</span>
                            </div>
                            <div><span class="tc-memo tips">有效期:${i.enabledAt!""}</span></div>
                            <div>
                                <span class="tc-memo tips">
                                    ${i.award.memo!""}
                                </span>
                            </div>
                        </div>
                        <div class="cell cell-score">
                            <div class="score">${i.award.score!""}</div>
                            <div class="tc-memo award-num">
                                <button class="btn-red btn-status-un" data-id="${i.id!""}">
                                    <#if i.status=1>已领取
                                    <#else>未领取
                                    </#if>
                                </button>
                            </div>
                        </div>    
                    </li>
                </#list>                        
            </ul>
            <div class="tc-list-footer" style="cursor:pointer;" id="loadmore" data-page="1" data-size="30">
                点击加载更多...
            </div>
        </div>
    </div>
    
    
<script type="text/javascript">

var validId = '${validId!""}';

    (function($){
    
        function bindClick() {
            $("#datalist button").unbind().bind("click", function() {
                var userAwardId = $(this).attr("data-id");
                if(userAwardId == "" || userAwardId == null){
                    swal({title:"请求错误,请稍候再试!", type: "warning"});
                }else{
                    window.location.href = 'malcUserDetails.do?userAwardId=' + userAwardId;
                }
            });
        }
        
        $("#loadmore").on("click", function() {
            
            $.ajax({
                url:'9999Ajax.do',
                type:'post',
                data:{
                    page:$("#loadmore").attr("data-page"),
                    rows:$("#loadmore").attr("data-size")
                    },
                datatype:'json',
                success:function(responseData){
                
                       var currentPage = responseData.data.currentPage;
                       var totalPages  = responseData.data.totalPages;
                       
                       if(currentPage <= totalPages) {

                           currentPage++;
                           $("#loadmore").attr("data-page", currentPage);

                       }
                       
                       if(responseData.data.rows.length <= 0){
                           $("#loadmore").html("暂无更多数据!");
                       }else{
                           var arrText = [];
                            for(i = 0; i < responseData.data.rows.length; i++){
                               var dataObj = responseData.data.rows[i];
                               
                            arrText.push('<li class="tc-list-item" >');
                                arrText.push('<div class="cell cell-logo">');
                                    arrText.push('<div class="logo">');
                                        arrText.push('<img src="'+dataObj.award.picUrl+'" alt="'+dataObj.award.name+'">');
                                    arrText.push('</div>');
                                arrText.push('</div>');
                                arrText.push('<div class="cell cell-award">');
                                    arrText.push('<div style="margin-top:10px;">');
                                        arrText.push('<span>'+dataObj.award.name+'</span>');
                                    arrText.push('</div>');
                                    arrText.push('<div><span class="tc-memo tips">有效期:'+dataObj.enabledAt+'</span></div>');
                                    arrText.push('<div>');
                                        arrText.push('<span class="tc-memo tips">');
                                            arrText.push(' '+dataObj.award.memo+' ');
                                        arrText.push('</span>');
                                    arrText.push('</div>');
                                arrText.push('</div>');
                                arrText.push('<div class="cell cell-score">');
                                    arrText.push('<div class="score">'+dataObj.award.score+'</div>');
                                    arrText.push('<div class="tc-memo award-num">');
                                        arrText.push('<button class="btn-red btn-status-un" data-id="'+dataObj.id+'">');
                                            if(dataObj.status == 1){
                                                arrText.push('已领取');
                                            }else{
                                                arrText.push('未领取');
                                            }
                                        arrText.push('</button>');
                                    arrText.push('</div>');
                                arrText.push('</div>');
                            arrText.push('</li>');
                            
                           }
                           $("#datalist").append(arrText.join(''));
                           bindClick();
                       }
                       
                },
                headers: {validId:validId},
                error: function(){
                    swal({title:"加载错误,请稍候再试!", type: "warning"});
                }
            });
        });
        
        bindClick();
    })(jQuery);

</script>
</@layout>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值