1. 程式人生 > >NodeJS案例-html對mysql增刪改查

NodeJS案例-html對mysql增刪改查

開始

下面案例需要安裝nodeJs(預設攜帶npm)才能執行。

這裡實現的案例是使用nodeJs + mysql + html 實現對資料的增刪改查。

1、建立專案

我在桌面建立了一個nodeJs-html-mysql-example的資料夾,進入資料夾順序執行下面命令:

npm install express --save

npm install cookie-parser

npm install mysql

2、 準備主檔案 main.js

var express = require('express');
var app = express();
var bodyParse = require('body-parser')
var cookieParser = require('cookie-parser') ;
var mysql = require('mysql');
var path = require('path')

app.use(cookieParser()) ;
app.use(bodyParse.urlencoded({extended:false})) ;
app.use(express.static(path.join(__dirname, 'static')))

//Mysql配置
var conn = mysql.createConnection({   
	host:'127.0.0.1',   
	user: 'root',   
	password: 'liguoqing',  
	database: 'test'}
);
conn.connect();
//conn.end();   


//跳轉到主頁
app.get('/',function(req,res){
    res.sendfile('public/index.html') ;
});

//跳轉到新增頁面
app.get('/add',function(req,res){
    res.sendfile('public/add.html') ;
});

//新增使用者
app.post('/addUser', function (req,res) {
	console.log("準備新增使用者");
	var name = req.body.name;
	var sex = req.body.sex;
	var age = req.body.age;
	
	var addSql = "INSERT INTO user(name,age,sex) VALUES(?,?,?)";
    conn.query(addSql, [name, age, sex], function(err, results, fields) {     
		if (err) {
			throw err;     
		}
		if(results) {         
			res.status(200).send(results) ;
		}       
		
	}); 
}) ;

//獲取所有的使用者
app.post('/getAllUser', function (req,res) {
	console.log("準備獲取所有的使用者");
	
	var selectSql = "SELECT * FROM user";
    conn.query(selectSql, function(err, results, fields) {     
		if (err) {
			throw err;     
		}
		if(results) {         
			res.status(200).send(results) ;
		}       
		
	}); 
}) ;

//刪除所選使用者
app.post('/delUser', function (req,res) {
	console.log("準備刪除所選使用者");
	
	var delId = req.body.id;
	var delSql = "DELETE FROM user WHERE id in ("+ delId +")";
	
	conn.query(delSql, function(err, results, fields) {     
		if (err) {
			throw err;     
		}
		if(results) {      
			console.log("成功");
			res.status(200).send({code : 0, msg : "ok"}) ;
		}  
	});
	
}) ;

//監聽3000埠
var server=app.listen(3000) ;

3、 使用者管理首頁 public/index.html

<html>
	<title>使用者管理</title>
    <style>
		a{
			text-decoration: none;
		}
	
		#operation a {
			border: 1px solid gray;
			padding: 5px 8px;
		}
	
		#main{
			margin-top: 10px;
		}
		#main table td{
			border: 1px solid red;
		}
		#main table td{
			text-align: center;
		}
		#main table tbody td:nth-child(1){
			width : 20px;
		}
		#main table tbody td:nth-child(2){
			width : 40px;
		}
		#main table tbody td:nth-child(3){
			width : 100px;
		}
		#main table tbody td:nth-child(4){
			width : 80px;
		}
		#main table tbody td:nth-child(5){
			width : 40px;
		}
		#main table tbody td:nth-child(6){
			width : 50px;
		}
    </style>
</head>
<body>
	<div id="operation">
		<a href="javascript:void(0)" onclick="batchDel()"><span>批量刪除</span></a>
		<a href="add"><span>新增</span></a>
	</div>
	<div id="main">
		<table>
			<thead>
				<td></td>
				<td>id</td>
				<td>名字</td>
				<td>年齡</td>
				<td>性別</td>
				<td>操作</td>
			</thead>
			<tbody></tbody>
		</table>
	<div>
</body>

<script src="jquery.min.js"></script>
<script type="text/javascript">
	$(document).ready(function(){
		//初始化頁面使用者資料
		$.post("getAllUser", function (data, status){
			if (status=='success'){
				$(data).each(function (){
					$("#main tbody").append(
						"<tr>" + 
						"	<td><input type=\"checkbox\" userId=\""+ this.id +"\"></td>" + 
						"	<td>"+ this.id +"</td>" + 
						"	<td>"+ this.name +"</td>" + 
						"	<td>"+ this.age +"</td>" + 
						"	<td>"+ (this.sex == 0 ? "男" : "女") +"</td>" + 
						"	<td><a href=\"javascript:void(0)\" onclick=\"del("+ this.id +", this)\">刪除</a></td>" + 
						"</tr>")
				});
			} else {
				alert('資料獲取失敗,請聯絡管理員...') ;
			}
		});
	});
	
	//刪除使用者
	function del(_id, _obj){
		$.post("delUser", {id : _id}, function (data, status){
			if (status=='success' && data.code == 0){
				alert("刪除成功");
				$(_obj).parents("tr").remove();
			} else {
				alert('資料刪除失敗,請聯絡管理員...') ;
			}
		});
	}
	
	//批量刪除使用者
	function batchDel(){
		//獲取打勾的多選框
		var $checked = $("#main tbody tr input[type='checkbox']:checked");
		if($checked.length > 0){
			var delIds = [];
			$($checked).each(function (){
				delIds.push($(this).attr("userId"));
			});
			$.post("delUser", {id : delIds.join(',')}, function (data, status){
				if (status=='success' && data.code == 0){
					alert("批量刪除成功");
					$checked.each(function (){
						$(this).parents("tr").remove();
					});
				} else {
					alert('資料批量刪除失敗,請聯絡管理員...') ;
				}
			});
		}else{
			alert("請選擇需要批量刪除的使用者");
		}
	}
</script>

</html>

4、使用者新增頁面 public/add.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>新增使用者</title>
</head>
<body>
	<div>
		<div>
			<span>姓名:</span>
			<span><input type="text" name="name"></span>
		</div>
		<div>
			<span>年齡:</span>
			<span><input type="number" name="age" value="20"></span>
		</div>
		<div>
			<span>性別:</span>
			<span>
				<input type="radio" name="sex" value="0" checked>男
				<input type="radio" name="sex" value="1">女
			</span>
		</div>
		<div><input type="button" id="save" value="儲存"></div>
	</div>
</body>
<script src="jquery.min.js"></script>
<script type="text/javascript">
	$("#save").click(function (){
		var name = $("input[name='name']").val();
		var age = $("input[name='age']").val();
		var sex = $("input[name='sex']:checked").val();
		
		if(!name){
			alert("請輸入姓名...");
			return;
		}
		
		var data = {
			name : name,
			age : age,
			sex : sex
		};
		
		$.post("addUser", data, function (data, status){
			if (status=='success'){
				alert("儲存成功");
				window.location.href = "/";//跳到主頁
			} else {
				alert('儲存使用者失敗,請聯絡管理員...') ;
			}
		});
	});
</script>
</html>

5、準備jquery static/jquery.min.js

6、啟動專案

在專案資料夾下面執行如下命令,即可啟動:

node main.js

結束

結尾:僅供自己學習,記錄問題和參考,若有帶來誤解和不便請見諒,共勉!