这个问题在这里已有答案:
我希望在jQuery ajax post请求之后渲染一个新模板。当我使用jquery / ajax发出请求时,我该怎么做?
这是发送邮件请求的初始路由。
@app.route("/data")
def data():
if request.method=='GET':
cursor.execute("SELECT * from data")
data = cursor.fetchall()
cursor.execute("DESCRIBE data")
headers = cursor.fetchall()
return render_template("data.html", data=data, headers=headers)
这是data.html中发送请求的jQuery
...
<script>
$(document).ready(function(){
$('.row').each(function(){
$(this).click(function(){
let rowId = $(this).attr('id');
var data_send = {'id' : rowId};
$.ajax({
type:'POST',
url: '{{ url_for('row') }}',
data : JSON.stringify(data_send),
dataType: "json"
})
})
})
});
</script>
这是接收post请求的方法:
@app.route('/row', methods=['POST'])
def row():
recieved_data = request.get_data().decode('utf8')
target_id = json.loads(recieved_data)['id']
cursor.execute("DESCRIBE data")
headers = cursor.fetchall()
cursor.execute("SELECT * from data")
data = cursor.fetchall()[int(target_id)]
return render_template("row.html",data = data, headers=headers)
即使服务器收到post请求没有问题,浏览器也不会重定向到row.html。我不想发回重定向URL和JSON,但实际上是渲染模板。
您可以使用html渲染模板(如html attribute)从ajax响应中设置$('#some_id').html(response)
。有关详细信息,请参阅以
...
<script>
$(document).ready(function(){
$('.row').each(function(){
$(this).click(function(){
let rowId = $(this).attr('id');
var data_send = {'id' : rowId};
$.ajax({
type:'POST',
url: '{{ url_for('row') }}',
data : JSON.stringify(data_send),
dataType: "json",
success: function(response) {
$(this).html(response);
}
})
})
})
});
</script>
view函数不允许GET请求,因此浏览器无法打开row.html。
尝试
@app.route('/row', methods=['GET', 'POST'])
def row():
data = None
headers = None
if request.methods == 'POST':
recieved_data = request.get_data().decode('utf8')
target_id = json.loads(recieved_data)['id']
cursor.execute("DESCRIBE data")
headers = cursor.fetchall()
cursor.execute("SELECT * from data")
data = cursor.fetchall()[int(target_id)]
return render_template("row.html",data = data, headers=headers)