JS按钮执行轨code [英] JS buttons to execute rails code
问题描述
我想有一个按钮,点击后,将执行轨code。有必要对这个JavaScript?有一些红宝石的JavaScript(.js.rb)?
I want to have a button that, when clicked, will execute rails code. Is javascript necessary for this? Is there some ruby-javascript (.js.rb)?
如果点击按钮...执行将
但是我不想重定向或去一个新的观点,只是Ruby来执行code。
if button is clicked... execute A However i do not want to redirect or go to a new view, just ruby code to be executed.
推荐答案
是的。尝试使用Google非侵入式JavaScript。随着轨具体有以下是一般原则(导轨3.0或更高版本),并且是最常用的形式。
Yes. Try googling unobtrusive javascript. With rails specifically the following is the general principle (rails v 3.0 or greater), and is most often used for forms.
下面是使用远程表来发表通过JavaScript一个消息的一个例子。
Here is an example of using a remote form to post a "message" via javascript.
首先设置您的控制器的JavaScript响应。因此,例如一个创造的行动将是这个样子:
First setup your controller to respond to javascript. So for example a "create" action would look something like this:
def create
@message = Message.new(params[:contestant])
#do whatever you want
respond_to do |format|
if @contestant.save
format.js
format.html { redirect_to(@message, :notice => 'Message was successfully created.') }
else
#deal with errors here/ redirect wherever you want
end
现在创建一个名为create.js.erb的文件。这是继轨命名控制器操作惯例,但要注意的js.erb扩展。
Now create a file called "create.js.erb". This follows the rails naming conventions for controller actions, but note the js.erb extension.
在此code,你可以把你想与任何回应Javascript以及钢轨3.1或缺省情况下可以使用jQuery为好。
In this code you can put whatever javascript you want to respond with, and in rails 3.1 or you can use jquery by default as well.
$(#messageform).html("<h3>Thanks for sending your message we will be in touch shortly</h3>");
然后在要启动这个JavaScript调用你会放一个表单你这样的观点:
Then in your view that you want to initiate this javascript call you would put a form like this:
<div id="messageform">
<%= form_for @message, :remote => true do |f| %>
<h2>Send us a message</h2>
<p>
<%= f.label :email %>
<%= f.text_field :email %>
</p>
<p>
<%= f.label :message %>
<%= f.text_area :message %>
</p>
<p>
<%= f.submit "Send message!"%>
</p>
<% end %>
</div>
这是一个标准的form_for。只有在这里特别要注意的事情是:在开始远程=> true参数
This is a standard form_for. Only thing special here to notice is the :remote => true parameter at the beginning.
不管怎么说希望这有助于:)
Anyways hope this helps :)
这篇关于JS按钮执行轨code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!