[英]Calling Rails action from Javascript
I have the this link_to
in my that calls the update
action in my controller: 我在我的调用我的控制器中的
update
操作的link_to
:
<%= link_to((image_tag("lock_closed.svg", :class => "edit")), :controller => "sections", :action => "update",:id => section.id, :remote => true) %>
But I would really like to call the update
action through some javascript with an ordinary image tag. 但我真的想通过一些带有普通图像标记的javascript调用
update
操作。
So something like: 所以类似于:
<%= image_tag("lock_closed.svg", :class => "edit")%>
and: 和:
$(".edit").click(function(){
if ($(this).hasClass("update")){
// call update action
} else {
//do something else
};
})
Is it possible to call an action this way? 是否可以通过这种方式调用动作? I've been finding a bit on using
GET
& POST
or Ajax
methods but I'm not sure how to utilise them to target a specific controller & action. 我一直在寻找使用
GET
和POST
或Ajax
方法,但我不知道如何利用它们来定位特定的控制器和动作。
Send an Ajax call 发送Ajax呼叫
$(".edit").click(function(){
if ($(this).hasClass("update")){
$.ajax({
type: "PUT",
url: "/sections/<%= section.id %>"
});
} else {
//do something else
};
})
In order to solve the issue of ActionController::InvalidAuthenticityToken
on the ajax call we should send also the authenticity_token
. 为了解决ajax调用中
ActionController::InvalidAuthenticityToken
的问题,我们还应该发送authenticity_token
。
$.ajax({
url: '/sections',
data: { authenticity_token: $('[name="csrf-token"]')[0].content,
id: <%= section.id %> },
method: 'POST',
success: function (res) {
....
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.