Ruby/Rails/AJAX/JQuery-在链接单击时,传递参数并执行控制器操作 [英] 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.
在我将link_to路由到名为"yes"的动作并传递我称为事件"的模型的ID之前,
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", 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我在这里找到了参考:从rails3中的javascript执行控制器/动作
S0 I found a reference here : execute controller/action from javascript in rails3
并查看了文档: http://api.jquery.com/jQuery. ajax/
然后想到了这个.如果从上面的前一条路线发布帖子成功,请更改链接的CSS类(更改颜色).
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).
$.ajax({
type: "POST",
url: "/user/" + $(this).attr('event') + "/yes/",
success: function(){
$(".like").click(function() {
if ($(this).hasClass("selected")) {
$(this).addClass("selected");
return false; }
});
我还添加了这是正在使用所需javascript的控制器的底部.
I also added this is the bottom of the controller that the desired javascript is being used.
respond_to do |format|
format.html { }
format.js
end
所以现在我的link_to看起来像这样
So now my link_to looks like this
<%= link_to "yes", yes_path(event), :class => "like", :remote => true %>
但是该页面仍在刷新,它看起来根本没有调用AJAX.
But the page is still refreshing and It doesnt look like its calling the AJAX at all.
- 我可以将参数"event"正确地传递为jquery属性吗?
- 我是否正确调用link_to? 这是我第一次来,所以我不知道自己在做什么错,可能是几件事?
- am I passing the parameter "event" properly as a jquery attribute?
- am I calling the link_to properly? This is my first time so I have no idea what I'm doing wrong, possibly a few things?
非常感谢您的帮助
推荐答案
这是您要的吗?
$(".like").click(function(evt) {
evt.preventDefault();
var $self = $(this);
$.post($self.attr("href"), function(response) {
$self.addClass("selected");
});
});
第一行使用like
类将JavaScript绑定到所有元素. preventDefault
是防止锚标记的默认行为(导航到href)的首选方法. $.post()
是$.ajax({ type: "POST" })
的简写.
The first line binds the JavaScript to all elements with a class of like
. preventDefault
is the preferred way to prevent the default behavior of an anchor tag (navigate to the href). $.post()
is shorthand for $.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.
丰富
这篇关于Ruby/Rails/AJAX/JQuery-在链接单击时,传递参数并执行控制器操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!