首頁 > web前端 > js教程 > 主體

node實作分頁查詢的方法

一个新手
發布: 2017-10-14 09:57:06
原創
2931 人瀏覽過


在本例中,用到的相關框架和範本包含:jade、mongoose、express、layui。

前台用的jade模板,這裡用了bootstrap佈局和layui的分頁控制項。
index.jade main code:

//文章列表显示
     p.container      
     if(articals.length > 0)
       p.container.clear
        - for(var i=0;i<articals.length;i++)
         .col-lg-6.col-md-6.col-sm-12
          p.panel.panel-default
           .panel-heading
             a.block.bold(href = &#39;/details?id=#{articals[i]._id}&#39;)= articals[i].title
           p.panel-body.height50!= articals[i].detail
           p.panel-footer
            span.glyphicon.glyphicon-user(aria-hidden = "true")
            span(style = "margin-right:20px;margin-left:5px;")= articals[i].author
            span= articals[i].createDate       //添加分页
       p#pager.text-center.col-lg-12 col-md-12 col-sm-12
       .empty
       .empty
       script(type="text/javascript").
         layui.use([&#39;laypage&#39;, &#39;layer&#39;], function(){
          var laypage = layui.laypage;
          laypage.render({
            elem: &#39;pager&#39;
            ,count: #{total}
            ,curr:(&#39;#{page}&#39;||1)
            ,jump: function(obj, first){
              if(!first){
                window.location.href = &#39;/index/&#39;+obj.curr;
              }
            }
          });
         });      else
       h2 快去发表一篇文章吧~  #footer
       .container.text-center
            p 版权所有 &copy; 2017 LorettaXiongField
登入後複製

index.js main code:

var express = require(&#39;express&#39;);  
var mongoose = require(&#39;mongoose&#39;);require(&#39;../models/schema&#39;);var article = mongoose.model(&#39;Article&#39;);var user = mongoose.model(&#39;User&#39;);var url = require(&#39;url&#39;);var router = express.Router();  
//处理get请求router.get(&#39;/&#39;, function(req, res, next) {  
  var con = [];
  article.find({}).exec(function(err, doc){
    var total = doc.length;    //按时间顺序查找前10条文章的数据
    article.find({}).sort({createDate: -1}).populate(&#39;creator&#39;, &#39;name&#39;).limit(10).exec(function(err, character){
    //添加容错措施
        if(err){
          console.log(err);
        }else if(character.length == 0){        //没有任何文章,就直接返回
          console.log(&#39;no articles!&#39;);
          res.render(&#39;index&#39;, { 
            title: &#39;首页&#39;, 
            articals : con
          });  
        }else{          for(var i = 0; i < character.length; i++){
            con[i] = {
              _id: character[i]._id,
              title: character[i].title,
              detail: character[i].text.replace(/<[\/]{0,1}[a-zA-Z\s"&#39;=;]{1,}>/g, &#39;&#39;),
              author: character[i].creator.name,
              createDate: character[i].createDate
            };
          }          //返回文章总数以及前10条数据
          res.render(&#39;index&#39;, { 
            title: &#39;首页&#39;, 
            total: total,
            articals : con
          });  
        }
      });
  })
});   

//处理带有页码参数的get请求router.get(&#39;/index/:page&#39;, function(req, res, next) {  
  var con = [];  var pageNum = parseInt(req.params.page);  var Creator;  if(pageNum){
  article.find({}).exec(function(err, doc){
    var total = doc.length;    //按时间顺序查找从第[(页码-1)*10]条数据开始的10条文章的数据
    article.find({}).sort({createDate: -1}).populate(&#39;creator&#39;, &#39;name&#39;).skip((pageNum-1)*10).limit(10).exec(function(err, character){
    //添加容错措施
        if(err){
          console.log(err);
        }else if(character.length == 0){
          console.log(&#39;no articles!&#39;);
          res.render(&#39;index&#39;, { 
            title: &#39;首页&#39;, 
            articals : con
          });  
        }else{          for(var i = 0; i < character.length; i++){
            con[i] = {
              _id: character[i]._id,
              title: character[i].title,
              detail: character[i].text.replace(/<[\/]{0,1}[a-zA-Z\s"&#39;=;]{1,}>/g, &#39;&#39;),
              author: character[i].creator.name,
              createDate: character[i].createDate
            };
          }          //返回新的页码以及相应的10条数据
          res.render(&#39;index&#39;, { 
            title: &#39;首页&#39;, 
            total: total,
            page: pageNum,
            articals : con
          });  
        }
      });
   });
  }
});   

module.exports = router;
登入後複製

下面附加app.js的主要程式碼:// 模組依賴var express = require('express' );
    

var path = require(&#39;path&#39;);
    var logger = require(&#39;morgan&#39;);
    var http = require(&#39;http&#39;);
    var favicon = require(&#39;serve-favicon&#39;);
    var mongoose = require(&#39;mongoose&#39;);
    var bodyParser = require(&#39;body-parser&#39;);
    require(&#39;./models/schema&#39;);
    var user = mongoose.model(&#39;User&#39;);
    var cookieParser = require(&#39;cookie-parser&#39;);
    var session = require(&#39;express-session&#39;);
    var app = express();
    //日志设置app.use(logger(&#39;dev&#39;));
    //图标设置app.use(favicon(path.join(__dirname, &#39;public&#39;, &#39;favicon.ico&#39;)));
    //视图设置app.set(&#39;view engine&#39;, &#39;jade&#39;);
    app.set(&#39;views&#39;, path.join(__dirname, &#39;views&#39;));
    //静态文件设置app.use(express.static(path.join(__dirname, &#39;public&#39;)));
    //表单数据解析app.use(bodyParser.json());
    app.use(bodyParser.urlencoded( {
    extended: true }
));
    //路由设置var routes = require(&#39;./routes/index&#39;);
    app.use(&#39;/&#39;, routes);
    //服务器设置var server = app.listen(8081, function () {
    var host = server.address().address var port = server.address().port console.log(&#39;server start on 127.0.0.1:8081&#39;);
}
)
登入後複製

以下是本人實現的效果:

第一次進入首頁:

node實作分頁查詢的方法

點選對應頁面的效果:

node實作分頁查詢的方法


#

以上是node實作分頁查詢的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板