我想在按钮列表上执行两种ajax方法,POST
和GET
。单击的按钮保留index
值,并将其传递给ajax GET触发的方法。
我能够执行调用GET
的'/download_file'
部分,但是我无法创建可以将POST
值传递给方法的ajax index
。
[我的函数在app.py
中(简化):
@app.route('/download_file', methods=['GET', 'POST'])
def save_doc():
index = request.form.get('index')
print(index)
和我的html:
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('a#test').bind('click', function() {
$.getJSON('/download_file',
function(data) {
//do nothing
});
return false;
});
});
</script>
<div>
<h1>messages list</h1>
<div>
<ol>
{%for index, message in enumerate(messages)%}
<li>{{ index }}{{ message.date }}-{{message.name}}</li>
<form>
<a href="" id=test><button id="btn" value="{{ index }}" class='btn btn-default'>Download</button></a>
</form>
{%endfor%}
</ol>
</div>
</div>
</body>
首先:您不需要<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