Первое: вам не нужно <a>
. Вы можете связать click
с <button>
Вам не нужно отправлять GET
. Вы можете получить index
от кнопки и отправить его в POST
, используя $.post()
.
$('button').bind('click', function() {
value = $(this).attr('value');
$.post('/download_file'
{'index': value},
function(data) {
//do nothing
});
return false;
});
Минимальный рабочий пример
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route('/')
def index():
data = [
{'date': 'dateA', 'name': 'nameA'},
{'date': 'dateB', 'name': 'nameB'}
]
return render_template_string('''
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('button').bind('click', function() {
value = $(this).attr('value');
$.post('/download_file', //?index=' + value,
{'index': value},
function(data) {
alert("Response: " + data);
});
return false;
});
});
</script>
<div>
<h1>messages list</h1>
<div>
<ol>
{%for message in messages %}
<li>{{ message.date }} - {{message.name}}</li>
<form>
<button id="btn" value="{{ loop.index0 }}" class='btn btn-default'>Download</button></a>
</form>
{%endfor%}
</ol>
</div>
</div>
</body>''', messages=data)
@app.route('/download_file', methods=['GET', 'POST'])
def save_doc():
print('method:', request.method)
index = request.form.get('index')
print('form["index"]:', index)
#print('args:', request.args)
#print('form:', request.form)
#print('data', request.data)
#print('files', request.files)
return "Server: " + str(index)
app.run() #debug=True