【问题标题】:Flash Message pop up without redirect没有重定向的 Flash 消息弹​​出
【发布时间】:2019-05-21 19:40:48
【问题描述】:

我正在尝试找到一种方法来让 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 重定向。

【问题讨论】:

    标签: python search flask crud


    【解决方案1】:

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

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

    【讨论】:

    • 警报中的数据,你的意思是使用searchString变量吗?
    • 没有输入确切的实际字符串“data” - 因为这是保存从服务器返回的信息的变量名 - 它来自这一行 - $.get("search/" + searchString, function(data). function(xxx)中的变量名xxx必须匹配alert命令中的变量-alert(xxx)
    • 是的,我只是在第一个函数中缺少函数(数据)。非常感谢!
    猜你喜欢
    • 2012-12-30
    • 1970-01-01
    • 2019-06-27
    • 2015-01-21
    • 2012-05-15
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    相关资源
    最近更新 更多