node学习十八:基于后端接口的前端渲染的应用(图书管理系统)

因为使用express提供的后台接口,可以使服务器端处理完数据后交给前端渲染到页面,而不是让服务器端完整的提供一个页面,涉及到前后端交互,将会使用到ajax

后台的数据处理:

router.js:

导入需要使用的模块:

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

处理路由:

// 提供所有的图书信息
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:

导入模块(db.js):

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

处理数据:

查询数据:

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.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});
        } 
    });
};

修改数据:

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,(result)=>{
        if(result.affectedRows == 1){
            res.json({flag : 1});
        }else{
            res.json({flag : 2});
        }  
    });
};

前端数据渲染:

index.html:

主体模块:

<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>

主体模块的dataList需要通过模板引擎渲染:

<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}}
</script>

添加图书(弹窗):

<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>

因为是弹窗,所以需要注意在css文件里面设置.form {display: none;}

编辑图书信息(弹窗):

<form class="form" id="editBookForm">
    <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>

index.js(需要引入jquery.js、template-web.js、dialog.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,是index.html能展示从后台获取到的数据:

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 = $('#editBookForm');
    // 先根据数据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();
                    }
                }
            });
        });
    });
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值