首页 > web前端 > js教程 > 正文

node实现分页查询的方法

一个新手
发布: 2017-10-14 09:57:06
原创
2934 人浏览过


在本例中,用到的相关框架和模板包含: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实现分页查询的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板