1. 程式人生 > 實用技巧 >Express示例(03):圖書管理系統-基於後端介面的前端渲染方式

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, '倚天屠龍記', '金庸', '傳統武俠', '大明王朝');