【发布时间】:2019-02-06 07:39:55
【问题描述】:
我想在 jQuery ajax 发布请求之后呈现一个新模板。当我使用 jquery/ajax 发出请求时,我该怎么做?
这是发送 post 请求的初始路由。
@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,而是实际呈现模板。
【问题讨论】: