文章目录
这个作业属于哪个课程 | <2301-计算机学院-软件工程社区-CSDN社区云> |
---|---|
这个作业要求在哪里 | <第二次作业–前后端交互计算器-CSDN社区> |
这个作业的目标 | <制作一个前后端交互计算器> |
其他参考文献 | <[JS-JSON-获取JSON对象中的数据展示到表格里_js接收json数据并展示_TSCCG的博客-CSDN博客](https://blog.csdn.net/TSCCG/article/details/119538650#:~:text=获取JSON对象中的emps属性,也就是存储所有学生信息的JSON数组,定义一个变量,遍历emps数组,将所有记录都以表格的格式拼接到这个变量里 将变量的值赋给tbody的innerHTML属性)> |
GitHub项目地址
前端:-/calculator.html at main · 102101243/- (github.com)
后端:-/app.py at main · 102101243/- (github.com)
PSP | Personal Software Process Stages | 预估耗时(分钟) | 实际耗时(分钟) |
---|---|---|---|
Planning | 计划 | 30 | 40 |
• Estimate | • 估计这个任务需要多少时间 | 30 | 40 |
Development | 开发 | 620 | 850 |
• Analysis | • 需求分析 (包括学习新技术) | 150 | 120 |
• Design Spec | • 生成设计文档 | 30 | 30 |
• Design Review | • 设计复审 | 30 | 50 |
• Coding Standard | • 代码规范 (为目前的开发制定合适的规范) | 30 | 50 |
• Design | • 具体设计 | 20 | 100 |
• Coding | • 具体编码 | 300 | 400 |
• Code Review | • 代码复审 | 30 | 50 |
• Test | • 测试(自我测试,修改代码,提交修改 | 30 | 50 |
Reporting | 报告 | 60 | 60 |
• Test Repor | • 测试报告 | 20 | 20 |
• Size Measurement | • 计算工作量 | 20 | 20 |
• Postmortem & Process Improvement Plan | • 事后总结, 并提出过程改进计划 | 20 | 20 |
合计 | 710 | 950 |
成果展示
计算器
功能1: 计算并把结果存入后端数据库
功能2: 回退清零
功能3:错误提示
功能4:读取历史记录
利率计算器
存款
贷款
设计实现过程
-
前端
- 使用HTML+CSS来设计界面
- JS来实现某些函数,比如获取计算历史数据时,将后端发送过来的JSON数据填入表格
-
后端
- 使用Flask来和前端进行交互
- 使用SQLite作为数据库,存储数据
-
前后端交互
- 利用Jquery的AJax进行数据前后端传递和交互
代码实现
前端:使用HTML+CSS + JS 进行页面设计
计算器
HTML
<div id="result"></div>
<h1>计算器</h1>
<div class="myDiv" title="计算器">
<input type="text" class="textbox" id="myInput" readonly>
<input type="text" class="memText" id="ansText" readonly>
<button class="button" id="myButton1" onclick="getButtonText(id)">1</button>
<button class="button" id="myButton2" onclick="getButtonText(id)" >2</button>
<button class="button" id="myButton3" onclick="getButtonText(id)" >3</button>
<button class="button" id="myButton+" onclick="getButtonText(id)" >+</button>
<button class="button" id="myButton-" onclick="getButtonText(id)" >-</button>
<button class="button" id="myButton4" onclick="getButtonText(id)">4</button>
<button class="button" id="myButton5" onclick="getButtonText(id)" >5</button>
<button class="button" id="myButton6" onclick="getButtonText(id)" >6</button>
<button class="button" id="myButton*" onclick="getButtonText(id)" >*</button>
<button class="button" id="myButton/" onclick="getButtonText(id)">/</button>
<button class="button" id="myButton7" onclick="getButtonText(id)">7</button>
<button class="button" id="myButton8" onclick="getButtonText(id)">8</button>
<button class="button" id="myButton9" onclick="getButtonText(id)">9</button>
<button class="button" id="myButton**" onclick="getButtonText(id)">**</button>
<button class="button button1" id="myButtonC" onclick="clearText()">C</button>
<button class="button" id="myButton." onclick="getButtonText(id)">.</button>
<button class="button" id="myButton0" onclick="getButtonText(id)">0</button>
<button class="button" id="send-request" onclick="getData()"> = </button>
<button class="button" id="myButton(" onclick="getButtonText(id)">(</button>
<button class="button" id="myButton)" onclick="getButtonText(id)">)</button>
<button class="button" id="myBack" onclick="backText()">Back</button>
<button class="button" id="myAns" onclick="dataAns()">ans</button>
<button class="button" id="myButtonSin" onclick="getButtonText(id)">sin</button>
<button class="button" id="myButtonCos" onclick="getButtonText(id)">cos</button>
<button class="button" id="myButtonTan" onclick="getButtonText(id)">tan</button>
</div>
.myDiv{
justify-content: center;
align-items: center;
float: left;
height: 500px;
width: 36%;
background-color: dodgerblue;
border-radius: 20px;
padding: 20px;
}
.button{
position: relative;
background-color: #4CAF50; /* Green */
border: none;
color: white;
top: 15px;
padding: 15px;
text-align: center;
text-decoration: none;
display: inline-block;
transition-duration: 0.4s;
cursor: pointer;
border-radius: 10px;
width: 70px;
height: 60px;
margin: 8px;
font-size: 20px;
left: 40px;
}
.button1 {
background-color: white;
color: black;
border: 2px solid #4CAF50;
}
.button1:hover {
background-color: #4CAF50;
color: white;
}
input[type="text"] {
width: 30vw; /* 设置文本框宽度为200像素 */
/* 设置文本框高度为50像素 */
opacity: 0.5;
}
input[type="number"]{
width: 150px;
}
.textbox {
position: relative;
top: 5%;
height: 40px;
left: 50%;
transform: translate(-50%, -50%);
font-size: 30px;
}
.memText{
position: relative;
top: 4%;
left: 50%;
transform: translate(-50%, -50%);
height: 30px;
font-size: 30px;
}
button {
text-align: center;
}
``
function clearText(){
var input = document.getElementById("myInput");
input.value = null
input = document.getElementById('ansText');
input.value = null
}
function backText(){
var input = document.getElementById("myInput");
input.value = input.value.substring(0,input.value.length-1);
}
function getButtonText(bName) {
var button = document.getElementById(bName);
var input = document.getElementById("myInput");
input.value = input.value += button.innerHTML;
}
function dataAns(){
$.ajax({
url: 'http://localhost:5000/ans',
type: 'GET',
success: function(response) {
document.getElementById("myAns").innerHTML = response['ans']
},
error: function(error) {
// Handle any error that occurred during the request
console.error('Error sending data:', error);
}
});
}
function getData(){
var iput = document.getElementById('myInput')
var inputData = iput.value;
var ansData = document.getElementById('ansText');
var data = {'data': inputData};
$.ajax({
url: 'http://localhost:5000/data',
type: 'POST',
data:JSON.stringify(data),
contentType:'application/json',
success: function(response) {
// Handle the response from the server
console.log('Data sent successfully:', response);
ansData.value = response['result']
},
error: function(error) {
// Handle any error that occurred during the request
console.error('Error sending data:', error);
}
});
}
function getHisData(){
$.ajax({
url: 'http://localhost:5000/hisData',
type: 'GET',
success: function(response) {
// Handle the response from the server
console.log('Data sent successfully:', response);
datas = response.datas
var htmlStr = "";
for(var i = 0;i < datas.length;i++){
data = datas[i];
htmlStr += "<tr>";
htmlStr += "<td>" + data.equation + "</td>";
htmlStr += "<td>" + data.result + "</td>";
htmlStr += "</tr>";
}
document.getElementById('hisContent').innerHTML = htmlStr;
},
error: function(error) {
console.error('Error sending data:', error);
}
});
}
function dataDelete(){
$.ajax({
url: 'http://localhost:5000/delete',
type: 'GET',
success: function(response) {
document.getElementById("hisContent").innerHTML = ''
console.log(response['data'])
},
error: function(error) {
// Handle any error that occurred during the request
console.error('Error sending data:', error);
}
});
}
利率
<div class="myDiv3">
<div>性别:
<label><input type="radio" name="way" value="存款">存款</label>
<label><input type="radio" name="way" value="贷款">贷款</label>
</div>
<body>请输入金额</body>
<input id="ipmoney" type="number" class="rate">
<br>
<body>请输入年限</body>
<input id="ipyears" type="number" class="time">
<button onclick="getInterest()" class="cl">确认</button>
<br>
<body>利息</body>
<input id="interest" type="number" style="opacity: 0.6" readonly>
<br>
<br>
<table border="1" align="center">存款利率表:
<button onclick="getCurrent()" class="cx">获取表格</button>
<thead>
<tr>
<th>年限
</th>
<th>利率</th>
</tr>
</thead>
<tbody id="current" align="center">
</tbody>
</table>
<table border="1" align="center">贷款利率表:
<button onclick="getLoan()" class="cx">获取表格</button>
<thead>
<tr>
<th>
年限
</th>
<th>
利率
</th>
</tr>
</thead>
<tbody id="loan" align="center">
</tbody>
</table>
</div>
CSS
.myDiv3{
position: relative;
float: left;
width: 25%;
height: 700px;
background-color: aqua;
border-radius: 40px;
padding: 20px;
}
table,th,td
{
margin: 20px;
border:1px solid orange;
width: 300px;
height: 30px;
}
.mtd{
border-radius: 20px;
background-color: deepskyblue;
width: 50px;
height: 35px;
}
.cl{
border-radius: 20px;
background-color: orange;
width: 50px;
height: 35px;
}
.cx{
border-radius: 20px;
background-color: orange;
width: 70px;
height: 35px;
}
JS
function getInterest(){
var radio = document.getElementsByName("way");
for (i=0; i<radio.length; i++) {
if (radio[i].checked) {
item = radio[i].value
}
}
if (item =='贷款'){
add = 'http://localhost:5000/intloan'
}else{
add = 'http://localhost:5000/intcurrent'
}
var ipm = document.getElementById('ipmoney').value;
var ipy = document.getElementById('ipyears').value;
var data = {'money': ipm, 'years': ipy};
$.ajax({
url: add,
type: 'POST',
data:JSON.stringify(data),
contentType:'application/json',
success: function(response) {
// Handle the response from the server
console.log('Data sent successfully:', response);
document.getElementById('interest').value = response['interest']
},
error: function(error) {
// Handle any error that occurred during the request
console.error('Error sending data:', error);
}
});
}
function getCurrent(){
$.ajax({
url: 'http://localhost:5000/current',
type: 'GET',
success: function(response) {
// Handle the response from the server
console.log('Data sent successfully:', response);
datas = response.datas
var htmlStr = "";
for(var i = 0;i < datas.length;i++){
data = datas[i];
htmlStr += "<tr>";
htmlStr += "<td>" + data.current + "</td>";
htmlStr += "<td>" + data.rate + "</td>";
htmlStr += "</tr>";
}
document.getElementById('current').innerHTML = htmlStr;
},
error: function(error) {
console.error('Error sending data:', error);
}
});
}
function getLoan(){
$.ajax({
url: 'http://localhost:5000/loan',
type: 'GET',
success: function(response){
// Handle the response from the server
console.log('Data sent successfully:', response);
datas = response.datas
var htmlStr = "";
for(var i = 0;i < datas.length;i++){
data = datas[i];
htmlStr += "<tr>";
htmlStr += "<td>" + data.timeLimit + "</td>";
htmlStr += "<td>" + data.rate + "</td>";
htmlStr += "</tr>";
}
document.getElementById('loan').innerHTML = htmlStr;
},
error: function(error) {
console.error('Error sending data:', error);
}
});
}
后端:使用Python+ Flask进行编写
各种函数
@app.route('/data', methods=['POST'])
def get_data():
# Retrieve data from the server
json_data = request.json
print(json_data)
try:
result = eval(json_data['data'])
except:
result = 'Error'
print(result)
if result != 'Error':
len_data = calData.query.count()
if len_data == 10:
calData.query.filter(calData.id == 1).delete()
cal = calData(equation=json_data['data'], result=result)
db.session.add(cal)
db.session.commit()
data = {'result': result}
#return jsonify({'message': 'Data received successfully'})
return jsonify(data)
@app.route('/ans', methods=['GET'])
def get_ans():
lne = calData.query.count()
rd = calData.query.filter(calData.id == lne)
ans = rd.result()
return jsonify({'ans': ans})
@app.route('/hisData', methods=['GET'])
def get_HisData():
# 获取历史记录
ghd = calData.query.all()
list_data = []
for i in ghd:
dic_data = {}
dic_data['equation'] = i.equation
dic_data['result'] = i.result
list_data.append(dic_data)
data = {'total': len(ghd), 'datas':list_data}
print(data)
return jsonify(data)
@app.route('/delete', methods=['GET'])
def data_delData():
calData.query.filter(calData.id >= 1).delete()
db.session.commit()
return jsonify({'data': 'Delete over!'})
@app.route('/current', methods=['GET'])
def getDeposit():
# 获取历史记录
ghd = depositRate.query.all()
list_data = []
for i in ghd:
dic_data = {}
dic_data['current'] = i.current
dic_data['rate'] = i.rate
list_data.append(dic_data)
data = {'total': len(ghd), 'datas':list_data}
print(data)
return jsonify(data)
@app.route('/loan', methods=['GET'])
def getLone():
# 获取历史记录
ghd = loanRate.query.all()
list_data = []
for i in ghd:
dic_data = {}
dic_data['timeLimit'] = i.timeLimit
dic_data['rate'] = i.rate
list_data.append(dic_data)
data = {'total': len(ghd), 'datas':list_data}
print(data)
return jsonify(data)
@app.route('/intloan', methods=['POST'])
def getintloan():
# 获取历史记录
money_years = request.json
money = float(money_years['money'])
years = float(money_years['years'])
if years == 0.5:
lr = loanRate.query.get(1)
elif years == 1:
lr = loanRate.query.get(2)
elif years > 1 and years <=3:
lr = loanRate.query.get(3)
elif years > 3 and years <5:
lr = loanRate.query.get(4)
else:
lr = loanRate.query.get(5)
rate = float(lr.rate)
interest = rate*money*years/100
return jsonify({'interest': interest})
@app.route('/intcurrent', methods=['POST'])
def getintcurrent():
# 获取历史记录
money_years = request.json
money = float(money_years['money'])
years = float(money_years['years'])
if years == 0.5:
lr = loanRate.query.get(1)
elif years == 1:
lr = loanRate.query.get(2)
elif years > 1 and years <= 3:
lr = loanRate.query.get(3)
elif years > 3 and years < 5:
lr = loanRate.query.get(4)
else:
lr = loanRate.query.get(5)
rate = float(lr.rate)
interest = rate * money * years/100
return jsonify({'interest': interest})
数据库
用Python+Flask+SQLite进行编写
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///D:\\PycharmProjects\\flaskProject1\\calData.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class calData(db.Model):
__tablename__ = 'calData'
id = db.Column(db.Integer, primary_key=True)
equation = db.Column(db.String(120), unique=False)
result = db.Column(db.Float, unique=False)
app.app_context().push()
class depositRate(db.Model):
id = db.Column(db.Integer, primary_key=True)
current = db.Column(db.String(120), unique=False)
rate = db.Column(db.String(10), unique=False)
class loanRate(db.Model):
id = db.Column(db.Integer, primary_key=True)
timeLimit = db.Column(db.String(120), unique=False)
rate = db.Column(db.String(10), unique=False)
db.create_all()
心得体会
通过这次的前后端交互制作计算器的作业,让我从根本上了解了什么是前后端交互。以及对前后端交互需要用到的东西都有了不少的了解,了解到Flask一个网页后端工具以及AJax前后端交互的便利以及其重要性,不光是后端,前端也是学习了HTML+CSS+JS感觉自己学到并且学会很多东西,并且意识到HTML的界面排版也是一门很深的学问。
result = db.Column(db.Float, unique=False)
app.app_context().push()
class depositRate(db.Model):
id = db.Column(db.Integer, primary_key=True)
current = db.Column(db.String(120), unique=False)
rate = db.Column(db.String(10), unique=False)
class loanRate(db.Model):
id = db.Column(db.Integer, primary_key=True)
timeLimit = db.Column(db.String(120), unique=False)
rate = db.Column(db.String(10), unique=False)
db.create_all()
# 心得体会
通过这次的前后端交互制作计算器的作业,让我从根本上了解了什么是前后端交互。以及对前后端交互需要用到的东西都有了不少的了解,了解到Flask一个网页后端工具以及AJax前后端交互的便利以及其重要性,不光是后端,前端也是学习了HTML+CSS+JS感觉自己学到并且学会很多东西,并且意识到HTML的界面排版也是一门很深的学问。