我正在设计一个表单来在基于 Flask 的数据库应用程序中创建家庭。基本上,用户可以在数据库中搜索客户,搜索结果的每一行都会有一个“添加”按钮。当用户单击该按钮时,客户端将出现在表单顶部的列表中。添加所有客户端后,用户可以单击另一个按钮来创建系列并将更改提交到数据库。
我成功地将“添加”按钮链接到 AJAX 请求,每当我单击它时,我都可以在控制台输出上看到它(带有正确的信息),但我一生都无法弄清楚如何从服务器返回所有必要的数据并将其写入模板。
我在下面添加了相关代码。我感觉错误出在我的路由函数中的某个地方,但由于我是 AJAX、jQuery 和 JavaScript 的新手,所以我很难准确地判断出了什么问题。请发送帮助!
路线.py
@app.route('/create_family', methods = ['GET','POST'])
def create_family():
prefill = {'created_by':current_user.id}
form = CreateFamily(data = prefill)
# This if block handles the client search
if form.validate_on_submit():
clients = Client.query
if form.first_name.data:
clients = clients.filter(Client.first_name.like('%{}%'.format(form.first_name.data)))
if form.last_name.data:
clients = clients.filter(Client.last_name.like('%{}%'.format(form.last_name.data)))
return render_template('create_family.html', form = form, clients = clients.all())
# Logic for the AJAX 'GET' request
elif request.method == 'GET':
if request.args.get('clientID'):
clientid = request.args.get('clientID')
# Queries DB for client information
client = Client.query.filter(Client.id == clientid).first()
# HTML to insert to the family table in the form
row = '<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>'.format(client.id,client.first_name,client.last_name,client.gen.gender,client.dob.strftime('%m-%d-%Y'))
# I'm not sure if this is right, or how I should change it
return jsonify(result=row)
else:
return render_template('create_family.html', form = form)
return render_template('create_family.html', form = form)
create_family.html
<html>
<head>
<link rel="stylesheet" href="{{ url_for('static', filename = 'styles/main.css') }}">
<script src="{{url_for('static', filename='javascriptfile.js')}}"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<!-- I omitted some of the template for brevity -->
<!-- This is the table I want to add to-->
<table class="familyView">
<tr class="familyHeader">
<th>Client ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Date of Birth</th>
</tr>
</table>
<!-- I omitted some of the template for brevity -->
<!-- This is the table I want to add to-->
<form action="" method="post"><br>
{% if clients %}
<table class="clientView">
<tr>
<th>Client ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Date of Birth</th>
</tr>
{% for c in clients %}
<tr>
<td class="clientID">{{ c.id }}</td>
<td>{{ c.first_name }}</td>
<td>{{ c.last_name }}</td>
<td>{{ c.gen.gender }}</td>
<td>{{ c.dob.strftime('%m-%d-%Y') }}</td>
<td><button class="addBtn" type ="button">Add</button></td>
</tr>
{% endfor%}
</table>
</form>
{% endif %}
javascriptfile.js
window.onload=function(){
$(".addBtn").click(function() {
var $recordToAdd = jQuery(this).closest('tr').find('.clientID').text();
console.log("clientid: " + $recordToAdd);
$.ajax({
cache: false,
url: 'create_family',
type: 'GET',
data: {'clientID': $recordToAdd,},
success: function(response) {
console.log(response);
},
error: function(error){
console.log(error);
}
})
});
}
最佳答案
这里有几个问题。首先也是最重要的,当我刷新页面时,我没有刷新 javascript。通过进行硬重置(Shift+F5),我能够解决其他一些问题。
其次,当我尝试在页面底部而不是顶部的表中追加一行时,我尝试使用不必要的 ajax 请求。该步骤只需使用 jQuery 即可完成
$(document).on("click", ".addBtn", function() {
var tr = $(this).closest('tr').clone();
tr.find("input").attr("class", "rmBtn");
tr.find("input").attr("value", "Remove from Family");
$(".familyView").append(tr);
});
第三,我必须重写routes.py
中的函数来更改我的方法的一些内容。我对其进行了更改,以便使用 AJAX 和 jQuery 显示搜索结果,这样每次进行新搜索时就不必刷新页面。
@app.route('/create_family', methods = ['GET','POST'])
def create_family():
prefill = {'created_by':current_user.id}
form = CreateFamily(data = prefill)
if (request.method == 'GET') and request.args.get('client_ids'):
ids = request.args.get('client_ids').split(',')
print('ids: {}'.format(ids), file = sys.stderr)
program = request.args.get('program')
if len(ids) != 0:
new_family = Family(program_id = program,
created_date = datetime.utcnow(),
created_by = current_user.id)
db.session.add(new_family)
db.session.flush()
fam_id = new_family.id
for cid in ids:
new_mem = FamilyMember(family_id = fam_id, client_id = cid)
db.session.add(new_mem)
data = {'message': 'Family {} created at {}'.format(fam_id, new_family.created_date), 'code':'SUCCESS'}
db.session.commit()
return make_response(jsonify(data), 201)
elif len(ids) == 0:
print('this is an error', file = sys.stderr)
data = {'message': 'Cannot create a family with no members', 'code':'ERROR'}
return make_response(jsonify(data), 401)
return render_template('create_family.html', form = form, client = client)
我知道这不是对我所修复的内容的最佳解释,但现在我已经离开原来的问题几天了,我记不清到底是什么给我带来了最大的麻烦。
关于javascript - 我想结合 jQuery、AJAX 和 Flask,但无法从服务器获取响应以在模板上写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60010687/