[英]How do I prevent Ajax from executing if my user isn't logged in?
I'm using Rails 4.2.7. 我正在使用Rails 4.2.7。 I have this set up for handling an action is a user clicks on an image on my page 我已设置此操作来处理操作,即用户单击我页面上的图像
<%= link_to image_tag('disk.png', :alt => 'Save'), my_object_create_path(:id => my_object.id), :class => 'link-save', title: 'Save', :remote => true %>
and then I have this coffee script for dealing with the call after the controller returns … 然后我有这个咖啡脚本来处理控制器返回后的呼叫…
$('a.link-save').on 'ajax:success', ->
$(this).closest('td').text('Saved')
The problem is, I don't want the above to execute if my user isn't logged in. I have this in my controller … 问题是,如果我的用户未登录,我不希望执行以上操作。我的控制器中有此文件……
respond_to do |format|
if logged_in? && my_object.save
flash[:notice] = 'Saved successfully'
format.json { render json: my_object, status: :created }
elsif !logged_in?
format.js { render js: "alert('not logged in');" }
else
format.json { render json: my_object.errors, status: :unprocessable_entity }
end
end
How do I prevent my ajax:success from executing if my user isn't logged in? 如果我的用户未登录,如何防止执行ajax:success?
I would modify the view, and only assign the class "link-save" if the user is logged on. 我将修改视图,并且仅在用户登录后才分配“ link-save”类。 The resulting JavaScript will not find the object to add the handler. 生成的JavaScript将找不到要添加处理程序的对象。 This will not cause javascript errors because jQuery selectors work fine if they find nothing. 这不会导致javascript错误,因为jQuery选择器在找不到任何内容时可以正常工作。
<%= link_to image_tag('disk.png', :alt => 'Save'),
my_object_create_path(:id => my_object.id),
:class => logged_in? ? 'link-save' : '',
title: 'Save', :remote => true %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.