【发布时间】:2018-09-05 09:23:28
【问题描述】:
所以我一直在 Flask 中工作,遇到了一个恼人的问题。我正在创建一个网站并使用该网站不切换页面的重定向功能。当不通过重定向调用时,我尝试去的每个地方都可以 render_template() 。这是我的代码(是的,hashed_password 没有经过哈希处理,我应该可能会重定向到下一个,但这些是另一天的问题):
@app.route('/logIn',methods=['Get', 'Post'])
def logIn():
_name = request.form['inputName']
_password = request.form['inputPassword']
# _hashed_password = bcrypt.hashpw(_password, bcrypt.gensalt( 12 ))
_hashed_password = _password
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("SELECT * FROM tbl_user WHERE user_name = '" + _name + "'")
user = cursor.fetchone()
print(user[0])
if len(user[2]) is not 0 and user[3] == _password:
active_user = User(user[0])
login_user(active_user)
return (redirect(url_for('home')))
else:
return json.dumps({'message': 'Username or Password not correct'})
@app.route('/Home')
@login_required
def home():
return render_template("home.html")
这一切都适用于 html 和 js 背景。 HTML 没有任何代码,仅包含要单击的按钮(尽管如果有帮助,我可以发布 html)。登录按钮的 JS 如下所示:
$(function() {
$('#btnLogIn').click(function() {
$.ajax({
url: '/logIn',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
});
最后,输出返回主页的 html,我想在浏览器中呈现的那个(这是输出):
<!DOCTYPE html>
<html lang="en">
<head>
<title>Python Flask Bucket List App</title>
<script src="static/js/jquery-3.3.1.min.js"></script>
<script src="static/js/logout.js"></script>
</head>
<body>
<form class="form-signout">
<button id="btnLogOut" class="btn btn-lg btn-primary btn-block" type="button">Log Out</button>
</form>
</body>
</html>
我一直在到处寻找。此外,在本地主机域调用与单击按钮后调用的 GET 相同的 GET 之后添加 /Home 并成功加载页面。如果有人知道如何通过加载“下一个”网址来做到这一点,那就更好了。
【问题讨论】:
-
不确定它会有所帮助,但您是否尝试在您的 ajax 函数中使用
url: '{{url_for(/login)}}'? -
而不是console.log(response),试试$("body").html(response) 看看它是否改变了什么?
-
@RambarunKomaljeet 那种工作!这呈现了新的 html!不幸的是,它保留在上一个链接中?我不知道如何描述它。它不会重定向到 /Home,但有那个 html。
-
@SamRosenberg 我知道你的意思;)。这是因为ajax就是这样工作的。尝试在成功函数中使用 javascript 重定向而不是 $("body").html。 (不确定这是否可行)
-
@RambarunKomaljeet 嗯。还是有问题。我无法复制它以注销,它仍然无法重定向实际的 url。我仍然不明白为什么重定向不能按预期工作。
标签: javascript python html flask