弹出Flash消息,无需重定向

时间:2019-05-21 19:40:48

标签: python search flask crud

我试图找到一种方法来弹出Flask闪烁的消息,而不必重定向页面。基本上,如果您输入匹配的助记符模式,它将搜索数据库并将其显示在搜索栏下方的警报中。

我尝试过完全删除重定向,但这使其无法正常工作。

将用户带到网址的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 个答案:

答案 0 :(得分: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

如果结果中有多个匹配项,则以上更改将仅发送最后一个匹配项。如果您想将所有匹配项组合到一个字符串中以发送给客户端以显示在警报中,则可能需要使用'message + =“而不是” message =“。