我最近了解了 Flask,我正在尝试编写一个小型网络工具来帮助我组织数据。在一页上,我打印了一张列表编号及其描述。我有 jQuery 脚本,它允许我双击我想要选择的内容,但我在请求使用 ajax 调用发布的数据时遇到问题。与此代码相关的所有内容都有效,唯一的异常(exception)是重定向到包含数据的新 URL。用于选择特定行并双击所有工作的 jQuery 代码,但我缺乏对使用 POST 和 ajax 请求发送回数据的掌握。我的最终目标是允许用户双击表中的特定行,它将第一列中的数字发送到下一页。当我运行这个时,什么也没有发生。
特定部分的 Flask python 代码在这里,
@app.route('/shelved/<user>', methods=['POST'])
def shelved(user):
userinfo = dict(name='name', user='name', email='name@email.com')
shelvedFiles = getInfo(user)
if request.method =='POST':
cl = request.form['cl']
return redirect(url_for('change', cl=cl))
return render_template('select_cl.html', userinfo=userinfo, shelvedFiles = shelvedFiles)
表格的 html 在这里:
<h2>Available Changelists for {{ userinfo.name }}</h2></br>
<table id="table">
<tr>
<th>CL #</th>
<th>Description</th>
</tr>
{% for entry in shelvedFiles %}
<tr>
<td>{{ entry.clnum }}</td>
<td>{{ entry.description }}</td>
</tr>
{% else %}
<li><em>No shelved changelists!</em></li>
{% endfor %}
</table>
以及相应的CSS:
.selected { background-color: #1B1B1B; font-color: black; }
我用来突出显示表格中的行的 javascript、双击的函数以及 ajax POST 调用都在这里,
<script>$(document).ready(function() {
$("#table tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
});
$('#table tr').on("dblclick", function(e){
var cl = $("#table tr.selected td:first").html();
$.ajax({
url: "{{ url_for('shelved', user=userinfo.user) }}",
data: {'cl' : cl},
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
});</script>
我原来的 ajax 调用是这样的,
$.ajax({
url: "{{ url_for('shelved', user=userinfo.user) }}",
data: {'cl' : cl},
type: 'POST',
success: function() {
console.log('success');
},
error: function(error) {
console.log(error);
}
});
我会在 Chrome 的开发人员选项卡中看到 POST 成功。因此,我将其更改为记录响应(我发布的原始 jQuery 代码),并且我可以在控制台中看到我想要重定向到的 url 的 html 以及正确传递的数据。我认为可能是我重定向到的页面和 Flask 函数有问题,但我编写了一个被黑客攻击的静态版本,它工作得很好。这只是当我包含 jQuery 和 ajax 调用时才开始。谁能看出我哪里出了问题吗?
最佳答案
因此,您使用 Ajax 将数据发送到 Flask 后端并获得响应,该响应是重定向到另一个页面。它没有按您预期的方式工作的原因是您在 Ajax 调用中收到 Flask 的响应。您将返回新的 URL,只是您没有对其执行任何操作。
$.ajax({
url: "{{ url_for('shelved', user=userinfo.user) }}",
data: {'cl' : cl},
type: 'POST',
success: function(data) {
console.log('success');
window.location.href = data; // navigate to the new URL
},
error: function(error) {
console.log(error);
}
});
关于jquery - 使用flask将带有ajax的表的值提交给python方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31080961/