我有一个flask项目,前端有5个文本框,分别是项目名称、项目金额、项目期限、保证金、手续费。项目逻辑是:前端在项目名称文本框中输入项目名称,然后后端根据输入的项目名称从SQLServer数据库中查询其他的值并显示在前端相应的文本框中。请写出该项目的前后端代码。
时间: 2024-03-17 17:41:05 浏览: 64
由于涉及到数据库查询以及Flask框架的使用,前后端代码较为复杂,我将分别给出前端页面和后端代码的示例。需要注意的是,以下代码仅供参考,具体实现方式因项目不同而异。
前端页面示例(使用Bootstrap框架):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask Project</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-4">
<form>
<div class="form-group">
<label for="project-name">项目名称</label>
<input type="text" class="form-control" id="project-name" placeholder="请输入项目名称">
</div>
<div class="form-group">
<label for="project-amount">项目金额</label>
<input type="text" class="form-control" id="project-amount" readonly>
</div>
<div class="form-group">
<label for="project-deadline">项目期限</label>
<input type="text" class="form-control" id="project-deadline" readonly>
</div>
<div class="form-group">
<label for="project-bond">保证金</label>
<input type="text" class="form-control" id="project-bond" readonly>
</div>
<div class="form-group">
<label for="project-fee">手续费</label>
<input type="text" class="form-control" id="project-fee" readonly>
</div>
</form>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function() {
$('#project-name').on('change', function() {
$.ajax({
url: '/project-info',
data: {project_name: $(this).val()},
dataType: 'json',
success: function(data) {
$('#project-amount').val(data.amount);
$('#project-deadline').val(data.deadline);
$('#project-bond').val(data.bond);
$('#project-fee').val(data.fee);
}
});
});
});
</script>
</body>
</html>
后端代码示例(使用Flask框架):
from flask import Flask, jsonify, request
import pyodbc
app = Flask(__name__)
# SQL Server数据库连接信息
server = 'localhost'
database = 'testdb'
username = 'sa'
password = 'password'
driver = '{ODBC Driver 17 for SQL Server}'
connection_string = f'SERVER={server};DATABASE={database};UID={username};PWD={password};DRIVER={driver}'
# 查询SQL
sql_query = '''
SELECT amount, deadline, bond, fee FROM projects WHERE name = ?
'''
# 建立数据库连接
def get_db_connection():
connection = pyodbc.connect(connection_string)
return connection
# 关闭数据库连接
def close_db_connection(connection):
connection.close()
# 查询项目信息
@app.route('/project-info')
def project_info():
project_name = request.args.get('project_name')
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute(sql_query, (project_name,))
result = cursor.fetchone()
close_db_connection(connection)
if result:
project_info = {
'amount': result[0],
'deadline': result[1],
'bond': result[2],
'fee': result[3]
}
return jsonify(project_info)
else:
return jsonify({'error': '项目不存在'})
if __name__ == '__main__':
app.run(debug=True)
在以上示例代码中,我们使用jQuery的ajax方法向后端发送请求,后端接收到请求后从数据库中查询相应的项目信息并返回结果,前端收到结果后将其显示在相应的文本框中。需要注意的是,以上仅为示例代码,实际项目中需要根据具体情况进行修改。
相关推荐
















