純手寫實現ajax分頁功能

前言

最近用到了這個功能,百度大半天,網上的不是有各類問題就是須要引入其餘的插件,無奈,只能本身寫,大體功能已經完成。前端頁面用bootstrap作樣式,分頁功能用ajax實現,沒用其餘插件哦,只引入引這些:javascript

<link href="bootstrap-3.3.7-dist/css/bootstrap.css" rel="stylesheet" />
    <script src="js/jquery-3.3.1.min.js" type="text/javascript"></script>
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js" type="text/javascript"></script>

簡介

相關概念:css

ajax:異步的javascript和xml 指的是在不刷新網頁的狀況下,能夠和服務器端通訊,局部刷新。html

bootstrap:Bootstrap 是最受歡迎的 HTML、CSS 和 JS 框架,用於開發響應式佈局、移動設備優先的 WEB 項目。前端

簡析 

主要思路就是寫兩個ajax方法,一個ajax方法負責更新頁數的同時調用另一個ajax方法,另外一個ajax方法負責加載頁面數據。java

代碼

<!doctype html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width,height=device-height,inital-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no">
    <title>文章列表</title>
    <link href="css/style.css" rel="stylesheet" />
    <link href="bootstrap-3.3.7-dist/css/bootstrap.css" rel="stylesheet" />
    <script src="js/jquery-3.3.1.min.js" type="text/javascript"></script>
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    function rows(np){ $.ajax({ url : '../article/rows', type : 'POST', dataType : 'json', /* data : params, */ success : function(data) { var pageCount = data%5 == 0 ? data/5 : (data/5+1); var codePage = ""; for (var j=np-2; j<=np+2; j++) { if(j > pageCount && j > 0){ codePage += 
                            "<li><a id='"+(j-5)+"' onclick='pages("+(j-5)+");rows("+(j-5)+");'>"+(j-5)+"</a></li>"; } } for (var j=np-2; j<=np+2; j++) { if(j >= 1 && j <= pageCount) { codePage += 
                            "<li><a id='"+j+"' onclick='pages("+j+");rows("+j+");'>"+j+"</a></li>"; } } for (var j=np-2; j<=np+2; j++) { if(j < 1 && j <= pageCount){ codePage += 
                            "<li><a id='"+(j+5)+"' onclick='pages("+(j+5)+");rows("+(j+5)+");'>"+(j+5)+"</a></li>"; } } $("#page-size").html(codePage); }, error : function() { alert("rows出錯了!"); } }); } function pages(p){ $.ajax({ url : '../article/page', type : 'POST', dataType : 'json', data : {"pageNow":p}, success : function(data) { var code = ""; for (var i=0; i<data.length; i++) { code += 
                    "<div>\r\n" + 
                    "<h2>\r\n" + 
                    " <a href='articleDetail.html?aid="+data[i].articleId+"'>"+data[i].articleTitle+"</a>\r\n" + 
                    "</h2>\r\n" + 
                    "<h5>\r\n" + 
                    " <span class=\"glyphicon glyphicon-calendar\" aria-hidden=\"true\">"+data[i].nowDate+"</span>&nbsp;&nbsp;\r\n" + 
                    " <span class=\"glyphicon glyphicon-user\" aria-hidden=\"true\">"+data[i].user.userName+"</span>\r\n" + 
                    "</h5>\r\n" + 
                    "<p>"+data[i].articleSummary+"</p>\r\n" + 
                    "<a href='articleDetail.html?aid="+data[i].articleId+"'>\r\n" + 
                    " <strong>More</strong>\r\n" + 
                    " <span class=\"glyphicon glyphicon-menu-right\" aria-hidden=\"true\"></span>\r\n" + 
                    "</a>\r\n" + 
                    "<hr />\r\n" + 
                    "</div>"; } $("#tableBody").html(code); }, error : function() { alert("page出錯了!"); } }); } $(document).ready(function () { rows(1); pages(1); }); </script>
</head>

<body>
    <nav class="navbar navbar-inverse" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-navbar-collapse">
                    <span class="sr-only">切換導航</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">動態</a>
            </div>
            <div class="collapse navbar-collapse" id="example-navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#"><span class="glyphicon glyphicon-user"></span> 註冊</a></li>
                    <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> 登陸</a></li>
                </ul>
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#">首頁</a></li>
                    <li><a href="#">動態</a></li>
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown"> 管理 <b class="caret"></b>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a href="#">文章</a></li>
                            <li><a href="#">評論</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <div class="container">
        <div class="row">


            <div class="col-xs-12 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1">

                <div class="list-group" id="tableBody">

                    <div>
                        <h2>
                            <a href="#">在教室內活動應注意安全</a>
                        </h2>
                        <h5> <span class="glyphicon glyphicon-calendar" aria-hidden="true">2018-02-10</span>
                            <span class="glyphicon glyphicon-user" aria-hidden="true">SpringBoot Redis</span>
                        </h5>
                        <p>在教室內活動,有許多看起來細微的事情值得同窗們注意,不然,在教室裏也一樣容易發生危險。如下就是幾個同窗們須要注意的幾點: 1. 防磕碰。目前大多數教室空間比較狹小,又置放了許多桌椅、飲水機等用品,因此不該在教室中追逐、打鬧,作劇烈的運動和遊戲,防止磕碰受傷。 2.防滑、防摔。教室地板比較光滑的,要注意防止滑倒受傷;須要登高打掃衛生、取放物品時,要請他人加以保護,注意防止摔傷。 3.防墜落。不管教室是否處於高層,都不要將身體探出陽臺或者窗外,謹防不慎發生墜樓的危險。 4.防擠壓。教室的門、窗戶在開關時容易壓到手,也應當到處當心,要輕輕地開關門窗,還先留意會不會夾到他人的手。 </p>
                        <a href="#">
                            <strong>More</strong>
                            <span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span>
                        </a>
                        <hr />
                    </div>
                    <div>
                        <h2>
                            <a href="#">在教室內活動應注意安全</a>
                        </h2>
                        <h5> <span class="glyphicon glyphicon-calendar" aria-hidden="true">2018-02-10</span>
                            <span class="glyphicon glyphicon-user" aria-hidden="true">SpringBoot Redis</span>
                        </h5>
                        <p>在教室內活動,有許多看起來細微的事情值得同窗們注意,不然,在教室裏也一樣容易發生危險。如下就是幾個同窗們須要注意的幾點: 1. 防磕碰。目前大多數教室空間比較狹小,又置放了許多桌椅、飲水機等用品,因此不該在教室中追逐、打鬧,作劇烈的運動和遊戲,防止磕碰受傷。 2.防滑、防摔。教室地板比較光滑的,要注意防止滑倒受傷;須要登高打掃衛生、取放物品時,要請他人加以保護,注意防止摔傷。 3.防墜落。不管教室是否處於高層,都不要將身體探出陽臺或者窗外,謹防不慎發生墜樓的危險。 4.防擠壓。教室的門、窗戶在開關時容易壓到手,也應當到處當心,要輕輕地開關門窗,還先留意會不會夾到他人的手。 </p>
                        <a href="#">
                            <strong>More</strong>
                            <span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span>
                        </a>
                        <hr />
                    </div>

                </div>
                <nav aria-label="Page navigation" class="text-center">
                    <ul class="pagination pagination-lg" id="page-size">
                        <li><a href="#">首頁</a></li>
                        <li><a href="#">&laquo;上一頁</a></li>
                        <li><a href="#">1</a></li>
                        <li><a href="#">2</a></li>
                        <li><a href="#">3</a></li>
                        <li><a href="#">4</a></li>
                        <li><a href="#">5</a></li>
                        <li><a href="#">下一頁&raquo;</a></li>
                        <li><a href="#">尾頁</a></li>
                    </ul>
                </nav>
            </div>
        </div>
    </div>
    <nav class="navbar navbar-default" role="navigation">
        <div class="container-fluid">
            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">Copyright &copy; 2019 &nbsp; 朱學良 &nbsp; 蒙ICP備15101216號-1 &nbsp;</a></li>
            </ul>
        </div>
    </nav>
</body>

</html>

後臺:處理數據(SSM框架寫的,看吧)jquery

package com.securty.imut.controller; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.sql.Timestamp; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.log4j.helpers.LogLog; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.securty.imut.bean.Article; import com.securty.imut.service.ArticleService; import com.securty.imut.util.WangEditor; @Controller @RequestMapping(value="/article") public class ArticleController { @Autowired private ArticleService articleService; /** * 查找全部 * @return
     */ @RequestMapping(value="/list") @ResponseBody public List<Article> list(){ List<Article> list = articleService.findAll(); return list; } /** * 查找 * @return
     */ @RequestMapping(value="/page") @ResponseBody public List<Article> page(HttpServletRequest request){ Article article = new Article(); Timestamp nowDate = new Timestamp(System.currentTimeMillis()); article.setNowDate(nowDate); String pn = request.getParameter("pageNow") == null ? String.valueOf(1) : request.getParameter("pageNow"); int pageNow = Integer.parseInt(pn); int pageSize = 5; int startRows = pageSize*(pageNow-1); List<Article> list = articleService.queryPage(startRows); return list; } /** * 查找 * @return
     */ @RequestMapping(value="/rows") @ResponseBody public int rows(HttpServletRequest request){ return articleService.getRowCount(); } @RequestMapping(value="/add") @ResponseBody public int add(Article article){ return articleService.addArticle(article); } @RequestMapping(value="/update") @ResponseBody public int update(Article article){ return articleService.updateArticleById(article); } @RequestMapping(value="/read") @ResponseBody public Article read(Article article){ return articleService.selectArticlesById(article); } @RequestMapping(value="/delete") @ResponseBody public int delete(Integer aid){ return articleService.deleteArticleById(aid); } @RequestMapping(value = "/upload",method=RequestMethod.POST) @ResponseBody public WangEditor uploadFile( @RequestParam("myFile") MultipartFile multipartFile, HttpServletRequest request) { try { // 獲取項目路徑
            String realPath = request.getSession().getServletContext() .getRealPath(""); InputStream inputStream = multipartFile.getInputStream(); String contextPath = request.getContextPath(); // 服務器根目錄的路徑
            String path = realPath.replace(contextPath.substring(1), ""); // 根目錄下新建文件夾upload,存放上傳圖片
            String uploadPath = path + "upload"; // 獲取文件名稱
            String filename = multipartFile.getOriginalFilename(); // 將文件上傳的服務器根目錄下的upload文件夾
            File file = new File(uploadPath, filename); FileUtils.copyInputStreamToFile(inputStream, file); // 返回圖片訪問路徑
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/upload/" + filename; String [] str = {url}; WangEditor we = new WangEditor(str); return we; } catch (IOException e) { LogLog.error("上傳文件失敗", e); } return null; } }

效果

參考地址

https://github.com/Aizhuxueliang/security   
git

相關文章
相關標籤/搜索