首页 > 解决方案 > 没有重定向的 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 重定向。

标签: pythonsearchflaskcrud

解决方案


您需要进行两项更改 - 一项在客户端显示警报框,一项在服务器端返回数据。

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 ="


推荐阅读