基于Flask框架,HTML5,CSS3,Javascript,完成一个评论区功能
时间: 2024-06-11 11:06:48 浏览: 240
1. 创建Flask应用程序,并导入相关库
```python
from flask import Flask,request,render_template,jsonify
from flask_sqlalchemy import SQLAlchemy
```
2. 配置数据库
```python
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost:3306/comment'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20))
content = db.Column(db.String(200))
```
3. 创建路由
```python
@app.route('/')
def index():
comments = Comment.query.all()
return render_template('index.html', comments=comments)
@app.route('/add_comment', methods=['POST'])
def add_comment():
username = request.form.get('username')
content = request.form.get('content')
comment = Comment(username=username, content=content)
db.session.add(comment)
db.session.commit()
return jsonify({'result': 'success'})
```
4. 编写HTML模板
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>评论区</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<div class="container">
<h1>评论区</h1>
<hr>
<form id="comment-form">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="content">评论内容</label>
<textarea class="form-control" id="content" name="content"></textarea>
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
<hr>
<div id="comment-list">
{% for comment in comments %}
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ comment.username }}</h5>
<p class="card-text">{{ comment.content }}</p>
</div>
</div>
{% endfor %}
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>
```
5. 编写Javascript代码
```javascript
$(function() {
$('#comment-form').submit(function(e) {
e.preventDefault();
$.ajax({
url: '/add_comment',
method: 'POST',
data: $(this).serialize(),
success: function(res) {
if (res.result == 'success') {
var username = $('#username').val();
var content = $('#content').val();
var comment = '<div class="card"><div class="card-body"><h5 class="card-title">' + username + '</h5><p class="card-text">' + content + '</p></div></div>';
$('#comment-list').prepend(comment);
$('#username').val('');
$('#content').val('');
}
}
});
});
});
```
6. 编写CSS样式
```css
.container {
margin-top: 50px;
}
.card {
margin-top: 20px;
}
```
7. 运行Flask应用程序
```python
if __name__ == '__main__':
app.run(debug=True)
```
8. 打开浏览器,访问http://localhost:5000,可以看到评论区页面,输入用户名和评论内容,点击提交按钮,即可添加一条评论。
阅读全文