javascript 从java脚本函数调用ruby函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11683028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
call ruby function from a java script function
提问by Suyog Sakegaonkar
I have written a ruby function and want to place it in js file, the js function should be able to give a call to ruby function and store the return value.
我写了一个ruby函数,想把它放在js文件中,js函数应该能够调用ruby函数并存储返回值。
Is it possible? How to do this task?
是否可以?这个任务怎么做?
采纳答案by Pritesh Jain
The Implementation you need depends on when are you calling the ruby code or function
您需要的实现取决于您何时调用 ruby 代码或函数
Is is while building or rendering a page or js?
Then you can you use the js with .erb extension .(as suggested by Super engineer) This allows you to call any ruby code and function available in views and application helpers.
eg demo.js.erb
var arr = "<%= call_function %>"
You need the function from client side? Then it is impossible to call the function directly, You need to use ajax for such scenarios. (as suggested by Spernsky Danil)
是在构建或渲染页面还是 js 时?
然后你可以使用带有 .erb 扩展名的 js。(如超级工程师所建议的)这允许你调用视图和应用程序助手中可用的任何 ruby 代码和函数。
例如 demo.js.erb
var arr = "<%= call_function %>"
您需要客户端的功能吗?那么直接调用函数是不可能的,这种场景就需要使用ajax了。(如斯佩恩斯基丹尼尔的建议)
回答by Danil Speransky
I think it is not possible, there are some reasons:
我认为这是不可能的,有以下几点原因:
- Browsers don't support Ruby
- JavaScript and Ruby have different system of types and I don't know any interface between them
- Also you cannot place JavaScript code and Ruby code in one file, because there is no mime type for such file
- 浏览器不支持 Ruby
- JavaScript 和 Ruby 有不同的类型系统,我不知道它们之间的任何接口
- 你也不能将 JavaScript 代码和 Ruby 代码放在一个文件中,因为这样的文件没有 MIME 类型
So I suppose you should convert your Ruby function to JavaScript funciton.
所以我想你应该将你的 Ruby 函数转换为 JavaScript 函数。
Or you may implement your Ruby function as a part of the Server API and call it from JavaScript by Ajax.
或者,您可以将 Ruby 函数实现为服务器 API 的一部分,并通过 Ajax 从 JavaScript 调用它。
回答by micnic
JavaScript is a client-side language and Ruby is a server-side language, they can't call each other directly, use AJAX or WS instead for communicating between server and client sides.
JavaScript 是客户端语言,Ruby 是服务器端语言,它们不能直接相互调用,而是使用 AJAX 或 WS 来进行服务器端和客户端之间的通信。
回答by Super Engineer
Well you can have js.erbfile. In which you can include ruby code. Just take a look at this code snippet from my project.
那么你可以有js.erb文件。您可以在其中包含 ruby 代码。看看我的项目中的这段代码片段。
$("#myModal").modal('hide');
<% if @status == "ok" %>
<%= add_gritter("We will contact you as soon as possible!", :image => :success, :class_name => "gritter-light") %>
<% else %>
<%= add_gritter("Something went wrong while saving you request. Please try again!", :image => :error, :class_name => "gritter-light") %>
<% end %>