如何通过Ajax渲染Flask应用接口返回的render_template模板响应?
问题原因
- 后端POST接口返回的是
render_template渲染完成的HTML字符串,不是包含redirect字段的JSON响应,前端尝试读取response.redirect时实际取到的是undefined,跳转不存在的地址自然会触发URL未找到报错。 - 现有逻辑矛盾:如果你需要跳转到新页面加载模板,不需要用Ajax接收完整HTML后再跳转;如果你需要在当前页加载模板内容,不需要调用
window.location.href执行跳转。
解决方案
提供两种符合不同需求的实现方案:
方案1:完成处理后跳转到新页面展示demo.html
这种方案适合需要独立页面展示结果的场景,修改逻辑如下:
后端Flask代码调整
from flask import jsonify, url_for @app.route("/execution_pipeline", methods=['POST', 'GET']) def execution_pipeline(): try: if request.method == 'POST': inputMap = request.get_json() print(inputMap) ### 你的业务处理代码 ### # 不再直接返回渲染模板,返回带跳转地址的JSON return jsonify({ 'redirect': url_for('execution_pipeline', location=minio_results_file_location) }) # 补充GET请求逻辑,用于渲染目标页面 if request.method == 'GET': location = request.args.get('location') return render_template('demo.html', location=location) except ReferenceError as e: return f"It is a {e} Provide proper reference of file path"
前端代码无需调整,原有Ajax逻辑可正常读取跳转地址执行跳转。
注意:如果
minio_results_file_location是敏感路径,不要直接放在URL参数中传递,可以存入session中获取,避免路径泄露。
方案2:在当前页面指定区域加载demo.html内容
这种方案适合无刷新更新页面内容的场景,修改逻辑如下:
后端Flask代码无需调整,保持原有返回render_template的逻辑即可。
前端Ajax代码调整
$.ajax({ type: "POST", url: "execution_pipeline", data: JSON.stringify(data), contentType : "application/json", success: function(response) { // 替换页面指定容器的内容为渲染后的demo.html代码 // 需提前在当前页面添加id为result-container的容器节点 $('#result-container').html(response); } });
内容的提问来源于stack exchange,提问作者Sai
相关产品推荐
相关产品推荐

