Я разрабатываю форму для создания семейств в приложении базы данных Flask. По сути, пользователь может искать клиентов в базе данных, и в каждой строке результатов поиска будет кнопка «Добавить». Когда пользователь нажимает кнопку, клиент появляется в списке в верхней части формы. После добавления всех клиентов пользователь может нажать другую кнопку, которая создаст семейство и зафиксирует изменения в базе данных.
Я успешно связал кнопку «Добавить» с запросом AJAX и вижу ее на выходе консоли (с правильной информацией) всякий раз, когда щелкаю по ней, но не могу на всю жизнь Я понимаю, как вернуть все необходимые данные с сервера и записать их в шаблон.
Я включил соответствующий код ниже. Я чувствую, что ошибка лежит где-то в моей функции маршрутизации, но, поскольку я новичок в AJAX, jQuery и JavaScript, мне трудно точно сказать, что происходит не так. Пожалуйста, отправьте помощь!
rout.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);
}
})
});
}