是否可以从javascript中调用Rails助手方法? [英] is it possible to call a rails helper method from within javascript?
问题描述
我的application.html.erb [查看文件]中有一个javascript代码块,该代码块接收来自外部api的事件.我要做的就是当事件在javascript代码块中收到时,我需要在[application_helper.rb]内部执行一个辅助方法.
I have a javascript code block in my application.html.erb [view file] which receives an event from external api. all i want to do is when the event is recieved in the javascript code block i need to execute a helper method inside [application_helper.rb].
我在这里浏览了大多数te堆栈,但是找不到任何相关的答案.
I have gone through most of te stacks in here but could not find any relevant answer.
javascript代码块如下所示:
the javascript code block looks like this:
var pusher = new Pusher('b00c9657a0a896f3ec26');
var channel = pusher.subscribe('NewOrders');
channel.bind('NewOrderArrived', function(data) {
[ I NEED TO CALL THE RAILS HELPER METHOD HERE ]
console.log("got u")
});
推荐答案
不直接,不.正如Dave Newton在评论中所说,Ruby在服务器上执行,而JS在客户端上执行.您想要做的是这样的:
Not directly, no. As Dave Newton said in the comment, Ruby executes on the server and JS executes on the client. What you'll want to do is something like this:
var pusher = new Pusher('b00c9657a0a896f3ec26');
var channel = pusher.subscribe('NewOrders');
channel.bind('NewOrderArrived', function(data) {
$.get('<%= url_for :some_controller_method_that_calls_helper %>', function(response){
// the response variable will contain the output of the controller method
});
console.log("got u")
});
这篇关于是否可以从javascript中调用Rails助手方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!