赞
踩
最终效果如图:通过修改表单,可以对数据库的内容增添改删。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>用户列表</title> <style> *{ margin: 0; padding: 0; box-sizing: border-box; text-align: center; } a{ text-decoration: none; color:white; } h6{ width: 80px; background-color: #2b71b8; line-height: 30px; border-radius: 3px; margin-bottom: 20px; } body{ display: flex; height: 100vh; justify-content: center; margin-top: 50px; } th,td{ border:1px solid #999; padding: 10px 15px; } th{ background-color: #f0f3f0; } table{ border-collapse: collapse; } td a{ margin-right: 2px; display: inline-block; width: 43px; height: 30px; line-height: 30px; border-radius: 4px; } td a:nth-of-type(1){ background-color: #e35d4a; } td a:nth-of-type(2){ background-color: #55a95a; } </style> </head> <body> <div class="container"> <h6> <a href="add">添加用户</a> </h6> <table> <tr> <th>用户名</th> <th>年龄</th> <th>爱好</th> <th>邮箱</th> <th>操作</th> </tr> <tr> <td>张三</td> <td>20</td> <td> <span>编程</span> <span>唱歌</span> <span>运动</span> </td> <td>zhangsan@qq.com</td> <td> <a href="" id="del">删除</a> <a href="" id="modify">修改</a> </td> </tr> </table> </div> </body> </html>
html 效果:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>添加用户</title> <style> .container{ width: 80vw; margin: 20px auto; } h3{ font-size: 29px; font-weight: normal; margin: 0; margin-bottom: 20px; } .form-group input{ width: 80vw; height: 20px; } label.label{ display: block; font-weight:600; margin: 10px 0; } button{ margin: 20px 0; background-color: #2f80bc; color:white; font-size: 17px; padding: 4px 8px; border:0; border-radius: 5px; cursor: pointer; } </style> </head> <body> <div class="container"> <h3>添加用户</h3> <form method="post" action="/add"> <div class="form-group"> <label class="label">用户名</label> <input type="text" id='name' name="name" class="form-control" placeholder="请填写用户名"> </div> <div class="form-group"> <label class="label">密码</label> <input type="password" id="password" name="password" class="form-control" placeholder="请输入密码"> </div> <div class="form-group"> <label class="label">年龄</label> <input type="number"name="age" id="age" class="form-control" placeholder="请填写年龄" max="120" min="0"> </div> <div class="form-group"> <label class="label">邮箱</label> <input type="email" name="email" class="form-control" placeholder="请输入邮箱" id="email"> </div> <div> <label class="label">请选择爱好</label> </div> <div id="checkbox-container"> <input type="checkbox" name="hobbies" id="bask" value="篮球"> <label for="bask">篮球</label> <input type="checkbox" name="hobbies" id="code" value="coding"> <label for="code">coding</label> <input type="checkbox" name="hobbies" id="ping" value="乒乓"> <label for="ping">乒乓球</label> <input type="checkbox" name="hobbies" id="sing" value="唱歌"> <label for="sing">唱歌</label> <input type="checkbox" name="hobbies" id="draw" value="画画"> <label for="draw">画画</label> </div> <button>添加用户</button> </form> </div> </body> </html>
要实现下面的代码,需要安装 node.js
和mongoDB
,并在终端中输入net start mongoDB
开启数据库。
而且还有安装第3方模块,nodeMon
:自动更新服务器;mongoose
: 在nodejs中方便的操控MongoDB数据库;cheerio
,在nodejs中用jquery的方式操控dom。
// 1.引入模块 const mongoose = require('mongoose'); const http = require('http'); const fs = require('fs'); const queryString = require('querystring'); const Url = require('url'); const cheerio = require('cheerio'); // 2.连接数据库 mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('数据库连接成功') }) .catch(err => { console.log(err) }); // 3.创建集合规则 const UserSchema = new mongoose.Schema({ name: { type: String, minlength: 2, maxlength: 20, required: true }, age: { type: Number, max: 120, min: 0 }, password: String, email: String, hobbies: [String] }) // 4.使用规则创建集合 const User = mongoose.model('User', UserSchema) let listHTML, addHTML; // 5.读取html页面上的数据 fs.readFile('list.html', 'utf-8', (err, result) => { if (err) return console.log(err); listHTML = result; }); fs.readFile('add.html', 'utf-8', (err, result) => { if (err) return console.log(err); addHTML = result; }) // 6.使用node的http模块创建服务器 // 用到了async和await,这样就可以先加载出所有数据再加载HTML http.createServer(async (req, res) => { const method = req.method; const url = req.url; // 8.2使用url模块来获取,true代表返回的query为对象类型 const query = Url.parse(url, true).query; if (method == 'GET') { if (url == '/') { // 从数据库中查询信息 let users = await User.find(); // 拼接HTML // 6.1拼接HTML的头部 let list = /<![\s\S]*<\/h6>/.exec(listHTML); list += ` <table> <tr> <th>用户名</th> <th>年龄</th> <th>爱好</th> <th>邮箱</th> <th>操作</th> </tr>` // 6.2拼接来的数据库中的数据 users.forEach(item => { list += `<tr> <td>${item.name}</td> <td>${item.age}</td> <td>` item.hobbies.forEach((hobby) => { list += `<span>${hobby} </span>` }) list += `</td> <td>${item.email}</td> <td> <a href="/remove?id=${item._id}" id="del">删除</a> <a href="/modify?id=${item._id}" id="modify">修改</a> </td> </tr>` }); // 6.3 拼接HTML的尾部 list += /<\/table>[\s\S]*<\/html>/.exec(listHTML); res.end(list); } // 7.1当用户点击主页面的添加按钮时响应添加按钮的页面 else if (url == '/add') { res.end(addHTML) } // 8.1修改用户信息 else if (url.includes('/modify')) { // 8.2 获取url路径中的id // 8.3 根据id查找用户信息 let user = await User.findOne({ _id: query.id }); // 8.3 准备好返回的html内容 const reg = new RegExp('添加用户', 'g') const modifyHTML = addHTML.replace(reg, '修改用户').replace('/add', `/modify?id=${user._id}`) // 8.4 使用第三方库cheerio,用服务器中的数据修改modifyHTML $ = cheerio.load(modifyHTML); $('#name').val(user.name); $('#age').val(user.age); $('#email').val(user.email); $('#password').val(user.password); $('#checkbox-container')[0]; $(':checkbox').each(function () { if (user.hobbies.includes($(this).val())) { $(this).prop('checked', 'check') } }); // 8.5将修改好的值返回给客户端 res.end($.html()); } // 9 删除用户信息 else if(url.includes('/remove')){ await User.findOneAndDelete({_id:query.id}); res.writeHead(301,{location:'/'}); res.end(); } } else if (method == 'POST') { // 7.2在add页面,用户点击提交表单时 if (url == '/add') { // 7.3接受用户提交的信息 let formData = ''; // 接受用户通过表单post的参数 req.on('data', (param) => { formData += param; }) req.on('end', async () => { let user = queryString.parse(formData); // 7.4将用户信息提交到数据库中 await User.create(user); // 301代表重定向,重定向到首页 res.writeHead(301, { location: '/' }); res.end(); }) } // 8.6 处理用户的修改提交 if (url.includes('/modify')) { let formData = ''; req.on('data', (param) => { formData += param; }); req.on('end', async () => { let user = queryString.parse(formData); await User.updateOne({ _id: query.id },user); res.writeHead(301,{location:'/'}); res.end(); }) } } }).listen('3000', () => { console.log('running at http://localhost:3000'); });
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。