python - 没有重定向的 Flash 消息弹出
问题描述
我正在尝试找到一种方法来让 Flask 闪烁的消息弹出而无需重定向页面。基本上,如果您输入一些匹配的助记符模式,它将搜索数据库并将其显示在搜索栏下方的警报中。
我已经尝试完全删除重定向,但这使它不起作用。
将用户带到 URL 的 javascript:
function search() {
var searchString = $("#inputSearch").val();
if (searchString.length == 4 && searchString.match(mnemonicPattern)) {
$.get("search/" + searchString, function () {
goToURL("search/"+searchString);
labCatalog.search(searchString, true, false).draw();
});
}
else if (searchString.length >= 6 && searchString.match(oracleNumberPattern)) {
$.get("search/" + searchString, function (data) {
goToURL("search/"+searchString);
labCatalog.search(searchString, true, false).draw();
});
}
else {
labCatalog.search(searchString).draw();
}
}
从数据库中获取数据的搜索功能:
@app.route('/search/<string:id_data>',methods=['GET'])
def search(id_data):
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM sims WHERE mnemonic=%s", [id_data])
result = cur.fetchall()
cur.close()
for match in result:
message = "Mnemonic: " + str([match[0]]) + ' Description:
+ str([match[1]]) + ' RFT Date: ' + str([match[2]])
flash(message)
return redirect(url_for('Index'))
我只想弹出 Flash 消息,而不必使用 localhost/search/mnemonicpattern 重定向。
解决方案
您需要进行两项更改 - 一项在客户端显示警报框,一项在服务器端返回数据。
1)在客户端更改
goToURL("search/"+searchString);
到
alert(data)
2)在服务器端更改
message = "Mnemonic: " + str([match[0]]) + ' Description:
+ str([match[1]]) + ' RFT Date: ' + str([match[2]])
flash(message)
return redirect(url_for('Index'))
到
message = "Mnemonic: " + str([match[0]]) + ' Description: '
+ str([match[1]]) + ' RFT Date: ' + str([match[2]])
return message
如果 result 中有多个匹配项,则上述更改将仅发送最后一个匹配项。如果要将所有匹配项合并到一个字符串中发送给客户端以显示在警报中,则可能需要使用 'message +=" 而不是 "message ="
推荐阅读
- python - for 循环使用上一项通过标准输入
- r - 如何在不重复 mutate 多次的情况下改变 dplyr 中的许多列?
- azure - 无法获取 Azure 负载均衡器池的 resourceId
- google-chrome - 如何让我的测试扩展在其他网站上运行?
- analytics - Rasa 的分析工具
- tensorflow - 如何获得“检测到”对象的概率值?
- javascript - 了解如何更改 Javascript 属性
- python - 将列表列转换为 2D numpy 数组
- dart - 滚动时 SliverAppBar 内容消失
- go - OAuth 2 和管理服务器端的多个用户访问令牌