Jquery & Rails 3:从js文件运行控制器操作?
我想单击页面上的 div 来运行一定数量的 javascript 任务,同时也在控制器上运行操作。更详细地解释一下:
我有一个 untitled.js 文件,其中放置了一堆 jquery 代码:
$(function(){
$('nav li').hover(function(){
$(this).addClass("bigger", 50);
}, function(){
$(this).removeClass("bigger", 50);
});
$('#notify').click(function(){
$('.notifications').show();
});
$('#notify').click(function(){
(some code to run a controller action)
});
});
我想在单击 #notify 按钮时在“Users”控制器上运行一个名为“run_tasks”的控制器操作,以及显示通知类。正如您在上面的代码中看到的,我有用于显示 .notifications 的 jquery 代码,但我不知道要在“(运行控制器操作的一些代码)”中放入什么。为了提供有关控制器操作的信息,它只会运行一些我想要运行的任务,它不会重定向到新页面或任何内容。这是用户控制器的基本格式:
class UsersController < ApplicationController
....
def run_tasks
end
end
我想要做的事情是否可能,如果可以,我应该在其中放入什么 jquery 代码?我正在使用 Rails 3.0.9 和最新的 jquery。
I would like to click a div on a page to run a certain number of javascript tasks, but also to run an action on a controller. To explain in greater detail:
I have a untitled.js file in which I have put a bunch of jquery code :
$(function(){
$('nav li').hover(function(){
$(this).addClass("bigger", 50);
}, function(){
$(this).removeClass("bigger", 50);
});
$('#notify').click(function(){
$('.notifications').show();
});
$('#notify').click(function(){
(some code to run a controller action)
});
});
I would like to run a controller action called "run_tasks" on the "Users" controller when the #notify button is clicked, as well as showing a notifications class. As you can see in the above code I have the jquery code for showing .notifications sorted out, but I don't know what to put in "(some code to run a controller action)". To provide information about the controller action, it will just run some tasks that I want to run, it doesn't redirect to a new page or anything. Here is the basic format of the users controller:
class UsersController < ApplicationController
....
def run_tasks
end
end
Is what I am trying to do possible, and if so what jquery code do I put in there? I'm using Rails 3.0.9 and the newest jquery.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要您有该控制器操作的路由,您就可以通过使用 jQuery 的 $.get()。
也不需要执行两个
$('#notify').click()
,您可以将这两个语句放在一个块中(就像我在上面的代码片段中所做的那样)。请注意,在这种情况下
.get()
只是发出调用服务器上控制器操作的请求并忽略结果,但您也可以使用它来处理控制器返回的数据。请参阅上面的文档链接。As long as you have a route for that controller action, you can cause it to run by simply issuing an ajax request to it with jQuery's $.get().
There's no need to do two
$('#notify').click()
either, you can put the two statements in one block (as I have done in the code snippet above).Note that in this case
.get()
simply makes the request to call the controller action on the server and ignores the result, but you can also use it to handle data returned by the controller. Refer to the doc link above.