防止页面被打开

时间:2013-08-21 14:12:45

标签: ruby-on-rails ruby-on-rails-3.2

当用户点击图表时,我会在其ID事件的Javascript端获得一些onclick,并将其作为查询参数传递给我想要的页面打开,我说

window.open(go_to);

其中goto将包含该查询参数,例如"http://localhost:3000/myapp/people?provider=134"

所以现在它命中了Rails端的index动作方法,在那里我还为登录用户获得了另一个变量:

def index
  cur_user_id = current_user.id
  provider_id = params[:provider]

  # call the REST service and pass those two params
  # and get the appropriate JSON back from the service

  if provider_id == cur_user_id
    render nothing: true
  end
end

我遇到的问题是这个逻辑:

  if provider_id == cur_user_id
    render nothing: true
  end

所以如果登录用户与我不想打开该页面或显示任何内容的提供商相同。 Render Nothing正在帮助不显示任何内容,但仍然是来自Javascript的window.open部分代码正在打开页面,空白 我怎么能告诉它,甚至不打开新页面?

1 个答案:

答案 0 :(得分:0)

您可以使用与javascript混合的ruby代码:

var provider_id = $('#provider_id').val();
var go_to = '/path/to/somewhere?provider_id=' + provider_id;
if(provider_id == <%= current_user.id %>) {
  alert('You cannot go there!');
} else {
  window.open(go_to);
}

请记住,ruby代码将首先执行(在服务器端),然后生成HTML / javascript,最后在客户端执行。所以javascript中的<%= current_user.id %>只会在那里打印出值,就像在JS中硬编码一样。


看来你不知道javascript部分里面的ruby代码,举个例子,在你的一个视图中使用Javascript试试这个:

# this is on the server-side, it will be generated:
<script type="text/javascript">
  <%= "alert('hello Eric!');".html_safe %>
</script>

# on the client-side, you will receive this generated HTML content:
<script type="text/javascript">
  alert('hello Eric!');
</script>

对于HAML:

:javascript
  #{"alert('hello Eric')".html_safe}
  var hello = '#{"hello World!"}';
  alert(hello);
相关问题