[英]Ruby/Rails/AJAX/JQuery - On link click, passing a parameter and performing a controller action
I'm trying to use clicking a link to perform and action in my controller called 'yes' but do so client side rather than having to refresh everytime a user clicks. 我试图使用单击链接在我的控制器中执行和操作,称为“是”,但这样做是在客户端,而不是每次用户单击时都刷新。
Before I had an link_to that routed to a action called "yes" and passed the id of a model I have called 'event' 在我将link_to路由到名为“ yes”的动作并传递模型ID之前,我将其称为“事件”
<%= link_to "yes", yes_path(event)%> (in view)
match 'user/:id/yes' => 'user#yes', :as => "yes" {in routes.rb)
The problem issue is that every time the user clicks the link the page refreshes while it performs the yes action, so it will flow alot smoother if I can tell the backend to perform the actions client side. 问题问题在于,每当用户单击链接时,页面就会在执行“是”操作时刷新,因此如果我能告诉后端执行客户端操作,页面将更加流畅。
S0 I found a reference here : execute controller/action from javascript in rails3 S0我在这里找到了参考: 从rails3中的javascript执行控制器/动作
and took a look at the documentation : http://api.jquery.com/jQuery.ajax/ 并查看了文档: http : //api.jquery.com/jQuery.ajax/
And came up with this. 并提出了这一点。 Where if the post is successful at the previous route from above change a css class for the link (change color). 如果帖子在上方的上一条路线上发布成功,请更改链接的CSS类(更改颜色)。
$.ajax({
type: "POST",
url: "/user/" + $(this).attr('event') + "/yes/",
success: function(){
$(".like").click(function() {
if ($(this).hasClass("selected")) {
$(this).addClass("selected");
return false; }
});
I also added this is the bottom of the controller that the desired javascript is being used. 我还添加了这是正在使用所需javascript的控制器的底部。
respond_to do |format|
format.html { }
format.js
end
So now my link_to looks like this 所以现在我的link_to看起来像这样
<%= link_to "yes", yes_path(event), :class => "like", :remote => true %>
But the page is still refreshing and It doesnt look like its calling the AJAX at all. 但是该页面仍然令人耳目一新,它看起来根本没有调用AJAX。
I'd really appreciate any help 我真的很感谢任何帮助
Is this what you're after? 这是你所追求的吗?
$(".like").click(function(evt) {
evt.preventDefault();
var $self = $(this);
$.post($self.attr("href"), function(response) {
$self.addClass("selected");
});
});
The first line binds the JavaScript to all elements with a class of like
. 第一行将JavaScript绑定到具有like
类的所有元素。 preventDefault
is the preferred way to prevent the default behavior of an anchor tag (navigate to the href). preventDefault
是防止锚标记的默认行为(导航到href)的首选方法。 $.post()
is shorthand for $.ajax({ type: "POST" })
. $.post()
是$.ajax({ type: "POST" })
简写。
Whatever you want to happen after a successful post to the server goes that finally function call. 成功发布到服务器后,无论您要发生什么,都将执行该最终函数调用。 The first argument is the response from the server. 第一个参数是服务器的响应。
Rich 丰富
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.