引用段落,本次代码演示的只有留言板的添加信息功能
思想方法:通过填写内容点击提交按钮,触发add请求,后台返回成功信息并且将数据存在Map之中,在add success回调函数中再调用obj.getlLst()方法,发送get请求,后台返回Map的数据,前端通过遍历数据显示在ul之中。
html部分:
<!DOCTYPE>
<html lang="zh-en">
<head>
<title>js实现简单留言板</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<link href="css/bootstrap.min.css" rel="stylesheet"/>
<link href="css/demo.css" rel="stylesheet"/>
<script src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/ajax2.js"></script>
</head>
<body>
<div class="container">
<div class="form-horizontal">
<div class="form-group">
<label class="col-sm-1 control-label">昵称:</label>
<div class="col-sm-11">
<input type="email" class="form-control name" id="inputEmail3" placeholder="请输入昵称">
</div>
</div>
<div class="form-group">
<label class="col-sm-1 control-label">留言:</label>
<div class="col-sm-11">
<textarea class="form-control message" rows="5" placeholder="请输入内容"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-11">
<button type="submit" class="btn btn-success submit">提交留言</button>
</div>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">留言列表</div>
<div class="panel-body">
<ul class="list-group messageList">
</ul>
</div>
</div>
</div>
</body>
</html>
请求部分代码:
let obj ={
//m:new Map(),
init:function(){
this.bind();
},
bind:function(){
$(".container .submit").click(()=>{
let _name = $(".name").val(),
_msg = $(".message").val();
if(_name =='' || _msg ==''){
alert('请输入信息')
}else {
//this.m.set(_name,_msg);
this.add(_name,_msg);
$(".name,.message").val('');
}
});
},
add:function(name,msg){
var self = this;
$.ajax({
type:'post',
url:'http://localhost:3000/add',
async:true, //异步
dataType:'json',
data:{name:name,message:msg},
success:function(res){ //后端返回的值
if(res.code == '200'){
obj.getList();
}
},
error:function(){
alert(1);
}
})
},
getList:function(name,msg){
var self = this;
$.ajax({
type:'get',
url:'http://localhost:3000/get',
sync:true,
dataType:'json',
success:function(res){
if(res.code == '200'){
let str = '';
for(let item of res.result){
str += `<li class="list-group-item">${item.name}<span>说:</span>${item.message}</li>`
};
$(".messageList").html(str);
}
}
})
},
}
$(function(){
obj.init();
})
node端代码:
引用段落,注意:运行node端需要安装中间件的依赖,通过提示缺失的包,使用cmd中npm install xxx即可,运行方法:node server-run.js(node文件的名称)
var connect = require('connect'); //创建连接
var bodyParser = require('body-parser'); //body解析
var m = new Map();
//map转为数组对象
function mapToArr(m){
var arr = [];
for(let [key,value] of m){
arr.push({name:key,message:value})
};
return arr;
};
var app = connect()
.use(bodyParser.json()) //JSON解析
.use(bodyParser.urlencoded({extended: true}))
//use()方法还有一个可选的路径字符串,对传入请求的URL的开始匹配。
//use方法来维护一个中间件队列
.use(function (req, res, next) {
//跨域处理
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*'); //允许任何源
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); //允许任何方法
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token'); //允许任何类型
res.writeHead(200, {"Content-Type": "text/plain;charset=utf-8"}); //utf-8转码
next(); //next 方法就是一个递归调用
})
.use('/add', function(req, res, next) {
console.log(req.body);
m.set(req.body.name,req.body.message);
var data = {
"code": "200",
"msg": "success"
};
res.end(JSON.stringify(data));
next();
//m.set(req.body.name,req.body.message);
//var data = {
// "code": "200",
// "msg": "success"
//};
//res.end(JSON.stringify(data));
//next();
//
})
.use('/get', function(req, res, next) {
var data={
"code": "200",
"msg": "success",
"result": mapToArr(m)
};
res.end(JSON.stringify(data));
next(); //
})
.use('/get_query', function(req, res, next) {
var data={
"code": "200",
"msg": "success",
"result":{"id":1}
};
res.end(JSON.stringify(data));
next(); //
})
.listen(3000); //
console.log('Server started on port 3000.');
运行效果:
2.get请求成功: 图2.get请求
3.页面显示: 图3.页面渲染成功
4.node端打印: 图4.node端显示
网友评论