![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1185bbb5c36b76ea2684e9d7a4b5acab.png)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>留言板</title>
<link rel="stylesheet" href="https://unpkg.com/bootstrap@4.1.3/dist/css/bootstrap.css">
</head>
<body>
<div class="container">
<h1 class="display-1">留言板</h1>
<hr>
<!-- <div id="loading">正在拼命加载数据.....</div> -->
<ul id="messages" class="list-unstyled">
</ul>
<hr>
<div class="form-group">
<label for="txt_name">称呼:</label>
<input class="form-control" id="txt_name" name="xxx" type="text">
</div>
<div class="form-group">
<label for="txt_content">留言:</label>
<textarea class="form-control" id="txt_content" cols="80" rows="10"></textarea>
</div>
<button type="button" id="btn_send" class="btn btn-primary">提交</button>
</div>
<script src="/lib/template-web.js"></script>
<script src="/lib/jquery-3.3.1.js"></script>
<!-- 渲染模板 -->
<script id="tpl" type="text/html">
{{each msgs}}
<li class="media">
<img class="mr-3" src="avatar.png" alt="{{$value.name}}">
<div class="media-body">
<h4>{{ $value.name }}</h4>
<p>{{ $value.content }} </p>
</div>
</li>
{{/each}}
</script>
<script>
function loadData() {
$.ajax({
type: 'get',
url: '/api/list',
success: function (data) {
var list = template('tpl', {
msgs: data
})
$('#messasges').html(list);
}
});
};
$('#btn_send').click(function () {
var name = $('#txt_name').val();
var content = $('#txt_content').val();
$.ajax({
type: 'post',
url: '/api/add',
data: {
name: name,
content: content
},
success: function (data) {
if (data === 'ok') {
loadData();
$('#txt_name').val('');
} else {
alert('发表失败');
}
}
});
});
</script>
</body>
</html>