我尝试创建一个用户登录的Web服务。我希望网页是动态的,所以我使用javascript jquery html和问题,如果我填写正确的值的用户名和密码,然后传递给另一个
127.0.0.1 - - [12 / Apr / 2015 08:54:42]" GET / login HTTP / 1.1" 200 -
127.0.0.1 - - [12 / Apr / 2015 08:54:51]" POST / login HTTP / 1.1" 405 -
this / loginuser
@APP.route('/loginuser', methods=['POST'])
def login():
error = None
con = mdb.connect('localhost','testuser', 'test623', 'test')
cur = con.cursor()
cur.execute("SELECT * FROM ADMIN")
rows = cur.fetchall()
login=False
for row in rows:
if request.form['username'] == row[0] and request.form['password'] == row[1]:
login=True
print request.form['username']
print request.form['password']
if login ==False:
error = 'Invalid Credentials. Please try again.'
response.result == error
else:
response.result == "success"
con.close

和此/ login
@APP.route('/login')
def login1():
return render_template('login1.html')

的script.js
function loginAndRedirect (){
var user = $('#txtUsername').val();
var pass = $('#txtPassword').val();
$.ajax({
url: '/loginuser',
data: $('form').serialize(),
type: 'POST',
dataType: 'json',
success: function(response){
if (response.result == "success") {
alert("You have been logged in!");
window.location.href="hello.html";
} else {
alert(result.details);
}
},
error: function(error){
console.log(error);
}
});
}

并登录:
<!DOCTYPE html>
<!--[if (gte IE 9)|!(IE)]><!--> <html lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title>MONOTORING_LAN</title>
<link href="static/css/style.css" rel="stylesheet">
<script src="static/js/jquery-1.9.0.js"></script>
<script src="static/js/script.js"></script>
</head>
<body>
<div class="container">
<section id="content">
<form method="POST" class="form-signin" role="form">
<h1>Login Form</h1>
<div>
<input type="text" id="txtUsername" placeholder="Username" name="username" required autofocus>
<input type="password" id="txtPassword" placeholder="Password" name="password" required autofocus>
<input class="btn btn-default" id = "submitButton" type="submit" value="Login">
</div>
</form><!-- form -->
{% if error %}
<p class="error"><strong>Error:</strong> {{ error }}
{% endif %}
</section><!-- content -->
</div><!-- container -->
</body>
<script src="static/js/script.js>
$(".form-signin").on("submit", function(e) {
e.preventDefault();
loginAndRedirect();});
</script>
</html>
&#13;
答案 0 :(得分:1)
问题是,您实际上从未将脚本挂钩到form
的{{1}}事件,因此表单由浏览器提交。但是,由于您没有指定submit
属性,因此表单会将自己提交到当前所在的网址(action
),从而产生您现在看到的405。将/login
发送到表单的loginAndRedirect
事件,您将不再发送到submit
端点:
/login
一些提示:
<script>
$(".form-signin").on("submit", function(e) {
e.preventDefault();
loginAndRedirect();
});
</script>
指向action
端点,这样即使您的JavaScript失败,用户仍然可以登录(除非您计划构建单页应用程序)/loginAndRedirect
子句,并按WHERE
和username
查看用户。不要将用户提供的值与SQL连接,而是使用参数化查询。password
对象(Flask没有提供回复,因此它是您项目的本地内容)。答案 1 :(得分:0)
我在login()
函数中看到的问题很少:
response
对象,无论如何你从哪里得到它? con.close
应为con.close()
,但我还应该关闭光标:
cur.close()
con.close()