javascript - 如何在 ajax 中呈现作为 Flask 应用程序响应发送的模板?
问题描述
我正在使用 Python Flask 应用程序,该应用程序将基本的 html 和 javascript 用于 Web 部件。
我正在使用 ajax 发布请求将数据从 UI 发送到后端。处理完数据后,我从 Python 烧瓶应用程序返回带有 render_template 的响应。但我无法理解如何在网络浏览器上使用 ajax 来呈现它。
python烧瓶API返回这个:
@app.route("/execution_pipeline", methods=['POST', 'GET'])
def execution_pipeline():
try:
if request.method == 'POST':
inputMap = request.get_json()
print(inputMap)
###I have my code here###
return render_template('demo.html', location=minio_results_file_location)
except ReferenceError as e:
return "It is a {} Provide proper referaece of file path"
“demo.html”是代码目录中的一个模板,我想在成功执行时加载它
而ajax函数如下:
$.ajax({
type: "POST",
url: "execution_pipeline",
data: JSON.stringify(data),
contentType : "application/json",
success: function(response) {
window.location.href = response.redirect;
}
});
但是在我们尝试加载此 Ajax 响应的网页上,我得到的 URL 未找到。
有什么解决办法吗?还是我做错了什么?
解决方案
从烧瓶中导入 jsonify 和 url_for:
from flask import jsonify, url_for
并尝试像这样返回到 ajax 调用:
@app.route("/execution_pipeline", methods=['POST', 'GET'])
def execution_pipeline():
try:
if request.method == 'POST':
inputMap = request.get_json()
print(inputMap)
###I have my code here###
return jsonify({'redirect': url_for('demo.html', location=minio_results_file_location)})
except ReferenceError as e:
return "It is a {} Provide proper referaece of file path"
推荐阅读
- c - 如何按特定顺序设置位域并稍后检查该顺序
- c# - 如果它来自不同的按钮事件,如何强制编译器不考虑任何代码块
- ios - 在向上滚动更改 tableview 标题
- magento2 - Mage2 :传递给 Magento\Paypal\Model\Adminhtml\Express::isOrderAuthorizationAllowed() 的参数 1 必须是 Magento\Sales\Model\Order\Payment 的实例
- java - 如何将推送通知的已读回执发送到 Android 上的 Amazon Pinpoint?
- tensorflow - 输入必须是4维[1,30,144,192,3],tensorflow训练出错
- php - 在 Laravel 或原始 SQL 中创建基于过滤器的搜索的最佳方法是什么?
- outlook - Outlook Web 加载项入口页面(taskpaneurl)可以知道哪个任务窗格按钮触发访问吗?
- html - 添加内容时,内联块 div 元素未垂直对齐
- bash - 获取 bash 脚本并通过反引号执行为变量赋值