我有一个 Rails 应用程序,它使用静态 html 页面(不在 app/views/ 中)向 Rails 服务器发送 AJAX 请求以进行登录和注销。
我使用会话进行用户身份验证,当用户登录时,session[:userid]
已设置并将响应“登录”发送回静态 html 页面。但是,当我单击注销按钮登录后,我发现session[:userid]
变成了nil
.
这是我的代码:
对于登录:
def login
# code here
if encrypt(params[:password]) == @user.password # authenticated
session[:userid] = @user.id
render :text => 'logged in'
else # wrong password
render :text => 'password not correct'
end
end
用于注销
def logout
# here session is no longer available
session[:userid] = nil
render :text => 'logged out'
end
登录页面:
<button id='login_button'>Log in</button>
<script type="text/javascript" charset="utf-8">
$('#login_button').click(function() {
$.ajax({
type: 'POST',
url: 'http://localhost:3000/user/login',
data: { username : $('#login_username').val() , password : $('#login_password').val() }
}).done(function(data) {
if (data == 'logged in') {
window.location = 'logged_in.html';
} else {
alert(data);
}
});
});
</script>
对于注销:
<button id='logout_button'>Log out</button>
<script type="text/javascript" charset="utf-8">
$('#logout_button').click(function() {
$.ajax({
type: 'POST',
url: 'http://localhost:3000/user/logout',
}).done(function(data) {
console.log(data);
});
});
</script>
登录日志:
Started POST "/user/login" for 127.0.0.1 at 2012-10-12 16:28:46 -0500
Processing by UserController#login as */*
Parameters: {"username"=>"name", "password"=>"[FILTERED]"}
User Load (0.1ms) SELECT "users".* FROM "users" WHERE (username = 'name')
Completed 200 OK in 12ms (Views: 0.3ms | ActiveRecord: 0.6ms)
注销日志:
Started POST "/user/logout" for 127.0.0.1 at 2012-10-12 16:28:50 -0500
Processing by UserController#logout as */*
{} <--------------------------------------- here I printed out session
Rendered text template (0.0ms)
Completed 200 OK in 1ms (Views: 0.7ms | ActiveRecord: 0.0ms)
是不是 AJAX 的问题,我们不能使用 session 来处理来自客户端的 AJAX 请求?
提前致谢。