Responding with js in Rails

拜拜、爱过 提交于 2019-12-13 04:24:35

问题


We have a link_to sending an ajax post, and are wondering if there's a way to change the content of the sending tag.

We basically want to update the database, then change the icon in the link_to block.

 <%= link_to add_favorite_path({type: type, id: id}), 
      type:"button", disable_with: '...', :method => :post, 
      :remote => true, class: 'btn btn-default btn-sm', id: "#{type}-#{id}" do %>
      <i class="fa fa-plus"></i>
<% end %>

Here's the favorites contoller:

class FavoritesController < ApplicationController
    respond_to :js

    def add
        @type = params[:type]
        @id     = params[:id]
        @selector = "#{@type}-#{@id}"    
    end
end

EDIT: add.js.erb:

var link = $("a#<%= @selector %>");
link.html('<i class="fa fa-check"></i>');

Found Solution: Could not alter the item html when using the disable_with: option. Removed it and it works.


回答1:


You can just make sure the appropriate controller reponds to JS

respond_to :js, :html

Then create the view file add.js.erb to add the appropriate JS to render the new icon. I would like to see more code but something like this

$("#id_of_link").html("<i class='fa fa-check'></i>");

Although, I usually create partials and escape_javascript to render the new partial in the JS



来源:https://stackoverflow.com/questions/21884419/responding-with-js-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!