我有一个网站,我需要一个JavaScript版本的“当前用户”对象以及ruby版本。我一直在分配这些变量做这样的事情...我如何有条件地将ruby变量赋值给javascript变量?
Application Controller:
def get_user
begin
@current_user = User.find(session[:user_id]) if session[:user_id]
@current_user_json = @current_user.to_json
rescue
session.delete(:user_id)
@current_user = nil
@current_user_json = {}
end
end
Web Page:
var current_user = null;
current_user_json = '<%= @current_user_json %>';
if(current_user_json != ''){
current_user = current_user_json.user;
}
即使有当前用户,我得到的当前用户是未定义的。可能是因为我将current_user_json
分配在单引号附近。但是,如果我不把它周围的单引号,我总是在没有用户登录一个JavaScript错误,因为语法无效 -
current_user_json = ;
我想我只是看着这个完全错误并且必须有更好的方法。鉴于这可能是一件常见的事情,我想获得其他人关于如何在JavaScript中创建一个与Ruby对象相同的对象的意见。
除“无”情况下,JSON不能只是空,或者作为问题笔记会出现Javascript语法错误。它应该像'{user:null}'一样。 – Pointy 2010-06-13 16:27:58
尖尖的 - 你的增加使这个答案工作。谢谢 – Tony 2010-06-13 16:35:39