最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Calling Rails action from Javascript - Stack Overflow

programmeradmin3浏览0评论

I have the this link_to in my that calls the update action in my controller:

<%= 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.

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.

I have the this link_to in my that calls the update action in my controller:

<%= 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.

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.

Share Improve this question asked Apr 9, 2013 at 5:42 Ryan KingRyan King 3,69612 gold badges49 silver badges73 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 18

Send an Ajax call

$(".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({
   url: '/sections',
   data: { authenticity_token: $('[name="csrf-token"]')[0].content, 
           id: <%= section.id %> },
   method: 'POST',
   success: function (res) {
     ....
  }
}); 
发布评论

评论列表(0)

  1. 暂无评论