Express示例(03):图书管理系统-基于后端接口的前端渲染方式

准备

dialog.js
jquery.js
template-web.js
地址:链接:https://pan.baidu.com/s/1DN8Nw5S_25DuZTiywVn17g 提取码:6666

安装

npm install express body-parser mysql --save

项目结构
mybook-restful
|-node_modules
|-public
|-css
|-style.css
|-img
|-js
|-diaglog.js
|-jquery.js
|-template-web.js
|-index.js
|-index.html
|-db.js
|-index.js
|-router.js
|-service.js
|-package.json

后端

index.js

/**
 * 实现图书管理系统后端接口
 */
const express = require('express');
const router = require('./router.js');
const bodyParser = require('body-parser');
const app = express();

//处理请求参数
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

app.use(router);
app.listen(3000,()=>{
    console.log('服务启动……');
});

router.js

/**
 *  * 
 * get      http://localhost:3000/books
 * get      http://localhost:3000/books/book
 * post     http://localhost:3000/books/book
 * get      http://localhost:3000/books/book/1
 * put      http://localhost:3000/books/book
 * delete   http://localhost:3000/books/book/2
 * 
 */

 const express = require('express');
 const router = express.Router();
 const service = require('./service');

 //提供所有的图书信息
 router.get('/books',service.allBooks);

 //添加图书信息时提交数据
 router.post('/books/book',service.addBook);

 //编辑图书时根据id查询相应信息
 router.get('/books/book/:id',service.getBookById);

 //提交编辑的数据
 router.put('/books/book',service.editBook);

 //删除图书信息
 router.delete('/books/book/:id',service.deleteBook);

 module.exports = router;

service.js

/**
 * 
 */

const db = require('./db');

exports.allBooks = (req, res) => {
    let sql = 'select * from book';
    db.base(sql, null, (result) => {
        res.json(result);
    });

};

exports.addBook = (req, res) => {
    let info = req.body;
    let sql = 'insert into book set ?';
    db.base(sql, info, (result) => {
        if (result.affectedRows == 1) {
            res.json({ flag: 1 });
        } else {
            res.json({ flag: 2 });
        }
    });
};

exports.getBookById = (req, res) => {
    let id = req.params.id;
    let sql = 'select * from book where id = ?';
    let data = [id];
    db.base(sql, data, (result) => {
        res.json(result[0]);
    });
};

exports.editBook = (req, res) => {
    let info = req.body;
    let sql = 'update book set name=?,author=?,category=?,description=? where id=?';
    let data = [info.name, info.author, info.category, info.description, info.id];
    db.base(sql, data, (results) => { 
 
        if (results.affectedRows == 1) {
            res.json({ flag: 1 });
        } else {
            res.json({ flag: 2 });
        }
    });
};

exports.deleteBook = (req, res) => {
    let id = req.params.id;
    let sql = 'delete from book where id = ?';
    let data = [id];
    db.base(sql, data, (result) => {
        if (result.affectedRows == 1) {
            res.json({ flag: 1 });
        } else {
            res.json({ flag: 2 });
        }
    });
};

前端
./public/js/index.js

$(function () {

    //初始化列表
    function initList() {
        $.ajax({
            type: 'get',
            url: '/books',
            dataType: 'json',
            success: function (data) {
                var html = template('indexTpl', { list: data });
                $('#dataList').html(html);

                //必须在渲染完成内容后才可以操作DOM标签

                $('#dataList').find('tr').each((function (index, element) {
                    var td = $(element).find('td:eq(5)');
                    var id = $(element).find('td:eq(0)').text();
                    //绑定编辑图书点击事件
                    td.find('a:eq(0)').click(function () {
                        editBook(id);
                    });

                    //绑定修改图书点击事件
                    td.find('a:eq(1)').click(function () {
                        deleteBook(id);
                    });

                    //绑定添加图书信息的单击事件
                    addBook();
                    //操作完成重置表单
                    var form = $('#addBookForm');
                    form.get(0).reset(); //不能重置隐藏域
                    form.find("input[type=hidden]").val(""); //重置隐藏域
                }));
            }
        });
    }

    //渲染列表数据
    initList();

    //删除图书信息
    function deleteBook(id){
        $.ajax({
            type:'delete',
            url:'/books/book/' + id,
            dataType:'json',
            success:function(data){
                //删除图书信息之后重新渲染数据列表
                if(data.flag == '1'){
                    initList();
                }
            }

        });
    }
    //编辑图书信息
    function editBook(id) {
        var form = $('#addBookForm');
        //先根据数据ID查询最新数据
        $.ajax({
            type: 'get',
            url: '/books/book/' + id,
            dataType: "json",
            success: function (data) {
                //初始化弹窗
                var mark = new MarkBox(600, 400, '编辑图书', form.get(0));
                mark.init();
                //填充表单数据
                form.find('input[name=id]').val(data.id);
                form.find('input[name=name]').val(data.name);
                form.find('input[name=author]').val(data.author);
                form.find('input[name=category]').val(data.category);
                form.find('input[name=description]').val(data.description);

                //对表单提交按钮重新绑定单击事件
                //解绑后重新绑定
                form.find('input[type=button]').unbind('click').click(function () {
                    //编辑完成数据之后重新提交表单
                    $.ajax({
                        type:'put',
                        url:'/books/book',
                        data:form.serialize(),
                        dataType:'json',
                        success:function(data){
                            if(data.flag == 1){
                                //隐藏弹窗
                                mark.close();
                                //重新渲染数据列表
                                initList();
                            }
                        }
                    });
                });

            }
        });
    }

    //添加图书信息
    function addBook() {
        $('#addBookId').click(function () {
            var form = $('#addBookForm');
            //实例化弹窗对象
            var mark = new MarkBox(600, 400, '添加图书', form.get(0));
            mark.init();

            form.find('input[type=button]').unbind('click').click(function () {
                $.ajax({
                    type: 'post',
                    url: '/books/book',
                    data: form.serialize(),
                    dataType: 'json',
                    success: function (data) {
                        if (data.flag == '1') {
                            //关闭弹窗
                            mark.close();
                            //添加图书成功后重新渲染数据列表
                            initList();
                        }
                    }
                });
            });
        });
    }
});

./public/index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图书管理系统</title>
        <link  rel="stylesheet" type="text/css" href="/www/css/style.css">
        <script type="text/javascript" src="/www/js/jquery.js"></script>
        <script type="text/javascript" src="/www/js/template-web.js"></script>
        <script type="text/javascript" src="/www/js/dialog.js"></script>
        <script type="text/javascript" src="/www/js/index.js"></script>
        <script type="text/template" id="indexTpl">
            {{each list}}
            <tr>
                <td>{{$value.id}}</td>
                <td>{{$value.name}}</td>
                <td>{{$value.author}}</td>
                <td>{{$value.category}}</td>
                <td>{{$value.description}}</td>
                <td><a href="javascript:;">修改</a>|<a href="javascript:;">删除</a></td>
            </tr>
            {{/each list}}
        </script>
</head>
<body>
    <div class="title">图书管理系统<a id="addBookId" href="javascript:;">添加图书</a></div>
    <div class="content">
        <table cellpadding="0" cellspacing="0">
            <thead>
            <tr>
                <th>编号</th>
                <th>名称</th>
                <th>作者</th>
                <th>分类</th>
                <th>描述</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="dataList"> 

            </tbody>
        </table>
    </div>

    <form class="form" id="addBookForm">
        <input type="hidden" name="id">
        名称:<input type="text" name="name"><br>
        作者:<input type="text" name="author"><br>
        分类:<input type="text" name="category"><br>
        描述:<input type="text" name="description"><br>
        <input type="button" value="提交">
    </form>
</body>
</html>

数据库
book.sql

/*
 Navicat Premium Data Transfer

 Source Server         : mybook
 Source Server Type    : MariaDB
 Source Server Version : 100506
 Source Host           : localhost:4406
 Source Schema         : book

 Target Server Type    : MariaDB
 Target Server Version : 100506
 File Encoding         : 65001

 Date: 27/10/2020 18:03:25
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `author` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `category` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `description` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 15 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES (2, '西游记', '吴承恩', '文学', '唐朝的故事');
INSERT INTO `book` VALUES (3, '三国演义', '罗贯中', '文学', '三国');
INSERT INTO `book` VALUES (4, '水浒传', '施耐庵', '文学', '宋朝');
INSERT INTO `book` VALUES (5, '红楼梦', '曹雪芹', '文学', '清朝');
INSERT INTO `book` VALUES (8, '倚天屠龙记', '金庸', '传统武侠', '大明王朝');
posted @ 2020-10-27 18:05  mrtransition  阅读(269)  评论(0)    收藏  举报