该系列文章索引:
本文,接着这篇文章继续,在这篇文章中实现的发布信息,取出信息列表的功能,本文,继续实现上文预留下的3个功能:
1,删除
2,编辑( ajax交互 )
3,分页与状态状态选中
实现后的效果:
CURD操作是比较简单的,稍微要费点精力的是分页和状态选中,以及弹窗+ajax实现信息更新.
index.jade( 模板 ):
1 doctype html 2 html 3 head 4 meta(charset='utf-8') 5 title todolist-by ghostwu 6 link(rel="stylesheet", href='./css/bower_components/bootstrap/dist/css/bootstrap.min.css') 7 script(src="./css/bower_components/jquery/dist/jquery.min.js") 8 script(src="./css/bower_components/bootstrap/dist/js/bootstrap.min.js") 9 script(src="./js/index.js")10 body11 div.container12 div.row13 div.col-md-offset-2.col-md-814 h3 留言板(node.js+mongodb+mongoose+jade) -by ghostwu15 form.form-horizontal(action='/add')16 div.form-group17 div.col-md-offset-2.col-md-818 textarea.form-control(name='msg',cols=60,rows=5)19 div.col-md-offset-2.col-md-820 button.btn.btn-primary 发布留言21 div.col-md-offset-2.col-md-822 ul.list-group23 - for ( var key in msgList ){24 li.list-group-item25 span #{msgList[key]['title']}26 a(href='/del/id/#{msgList[key]["_id"]}') 删除 | 27 input(type='hidden' value='#{msgList[key]["_id"]}')28 a(data-toggle='modal',data-target='#editMsg',href='javascript:;') 编辑29 - }30 div.col-md-offset-2.col-md-831 ul.pagination32 - for ( var i = 0; i < page; i++ )33 li34 a(href='/?p=#{i+1}') #{i+1}35 input(id='curP',type='hidden',value='#{curPage}')36 div.modal.fade#editMsg37 div.modal-dialog38 div.modal-content39 div.modal-header40 button(type='button',class='close',data-dismiss='modal') ×41 h4.modal-title 编辑信息42 div.modal-body43 textarea.form-control(name='msg-box',cols=60,rows=5)44 div.modal-footer45 button(type='button',class='btn btn-default',data-dismiss='modal') 关闭46 button(type='button',class='btn btn-primary',data-dismiss='modal') 更新
index.js( ajax交互与分页状态选中功能 ):
1 $(function(){ 2 /*---------------分页选中判断开始------------*/ 3 var curPage = $( "#curP" ).val(); 4 $( ".pagination a" ).each( function(){ 5 if ( $( this ).text() == curPage ) { 6 $( this ).parent().addClass( 'active' ) 7 .siblings( "li" ).removeClass( "active" ); 8 } 9 } );10 /*---------------分页选中判断结束------------*/11 12 /*---------------获取编辑信息开始------------*/13 $( "li.list-group-item a:last-child" ).on( 'click', function(){14 // console.log( $( this ).parent().find( "span" ).text() );15 var curId = $( this ).parent().find( "input" ).val();16 $( "#editMsg .modal-body textarea" ).val ( $( this ).parent().find( "span" ).text() );17 $( "#editMsg" ).find("input").remove();18 $( "#editMsg" ).append( "" );19 } );20 /*---------------获取编辑信息结束------------*/21 22 /*---------------更新信息开始---------------*/23 $( ".modal-footer .btn-primary" ).on( "click", function(){24 var curId = $( this ).parents( ".modal" ).find( ":hidden" ).val();25 var curMsg = $( this ).parents( ".modal" ).find( "textarea" ).val();26 $.ajax( {27 type : 'GET',28 url : '/update',29 data : { 'id' : curId, 'content' : curMsg },30 success : function( res ){31 location.href = 'http://localhost:3000';32 },33 error : function( res ){34 console.log( res );35 }36 } );37 } )38 /*---------------更新信息结束---------------*/39 });
server.js( 在上文的基础上,增加删除和更新2个路由功能 )
1 var express = require('express'); 2 var app = express(); 3 var path = require( 'path' ); 4 var indexRouter = require( './routers/index.js' ); 5 var addRouter = require( './routers/add.js' ); 6 var delRouter = require( './routers/del.js' ); 7 var updateRouter = require( './routers/update.js' ); 8 9 app.use( '/', indexRouter );10 app.use( '/add', addRouter );11 app.use( '/del', delRouter );12 app.use( '/update', updateRouter );13 app.use( express.static( path.join( __dirname, 'public' ) ) );14 15 app.set('views', path.join(__dirname, 'views'));16 app.set('view engine', 'jade');17 18 app.listen( 3000 );19 console.log( 'server listening on:' + 3000 );
index.js(在上文的基础上,新增分页和排序查询 )
1 var express = require('express'); 2 var router = express.Router(); 3 var Message = require('../db'); 4 5 function getAllMsg(curPage, pageSize) { 6 return new Promise(function (resolve, reject) { 7 Message.find({}, function (err, msgList) { 8 resolve(msgList); 9 }).skip( (curPage - 1) * pageSize ).limit( pageSize ).sort({ 'listTime': -1 });10 });11 }12 13 function Page( pageSize ) {14 return new Promise((resolve, reject) => {15 Message.count({}, (err, nums) => {16 resolve( Math.ceil( nums / pageSize ) );17 });18 });19 }20 21 router.get('/', function (req, res) {22 var p = req.query.p || 1; //当前页23 var pageSize = 5; //每页显示5条数据24 getAllMsg(p, pageSize).then(function (data) {25 Page(pageSize).then((nums) => {26 res.render('index', {27 msgList: data,28 page : nums,29 curPage : p30 });31 });32 });33 });34 35 module.exports = router;
update.js( 信息更新路由与数据更新操作 )
1 var express = require('express'); 2 var router = express.Router(); 3 var Message = require('../db'); 4 5 function updateMsg(msgInfo) { 6 return new Promise(function (resolve, reject) { 7 var condition = { '_id': msgInfo['_id'] }; 8 var data = { 'title': msgInfo['title'], 'listTime': msgInfo['listTime'] }; 9 Message.update(condition, data, function (err, result) {10 if (err) {11 reject( 'error' );12 } else {13 resolve( 'ok' );14 }15 });16 });17 }18 19 router.get('/', function (req, res) {20 updateMsg({21 title: req.query.content,22 listTime: new Date(),23 '_id': req.query.id24 }).then( function( status ){25 res.send( status );26 }, function( status ){27 res.send( status );28 });29 });30 31 module.exports = router;
del.js文件(删除信息的路由和数据库操作)
1 var express = require( 'express' ); 2 var router = express.Router(); 3 var Message = require( '../db' ); 4 5 function delMsg( id ){ 6 Message.remove( { '_id' : id }, function( err ){ 7 if( err ){ 8 console.log( err ); 9 }else{10 console.log( 'success' );11 }12 });13 }14 router.get('/id/:id', function( req, res ) {15 delMsg( req.params.id );16 res.redirect( '/' );17 });18 19 module.exports = router;