【问题标题】:Updating button text in Rails with ajax/jquery使用 ajax/jquery 在 Rails 中更新按钮文本
【发布时间】:2015-02-11 08:59:47
【问题描述】:

我查看了很多其他 SO 问题,但似乎无法使其正常工作。单击“完成”后,我希望按钮更新为“未完成”(仅示例文本)。实际操作很好(通过ajax),但我无法刷新按钮。我怀疑这是js的方式。任何建议表示赞赏。

现在是link_to。不过会是 button_to。

lessons_controller.rb

  def toggle_complete  
    @complete = Lesson.find(params[:id])  
    @complete.progress(current_user).toggle!(:completed)
    respond_to do |format|
      if @complete.save
        format.html { redirect_to @complete, notice: "'completed' updated" }
        format.js
      else
        redirect_to @complete, notice: "Not updated"
      end 
    end
  end

complete_button 部分(在课程#show 页面上)

<% if user_signed_in? && @lesson.progress(current_user).present? %>
    <div class="toggle-complete">
        <%= link_to complete_link_text(@lesson.progress(current_user)),   
                    toggle_complete_lesson_path(@lesson),   
                    :remote => true, class: "complete-link-single "
                     %>
    </div>
<% else %>
    <div class="complete-lesson">
        <%= link_to 'Complete', create_progress_lesson_path, :method => 'post', remote: true %>
    </div>
<% end %>

lesson_helper(根据属性决定“完成”或“未完成”)

def complete_link_text(completable)
    if completable.present?  
    completable.completed? ? 'Un-complete' : 'Complete'
  else
    'Un-complete'
  end
end  

toggle_complete.js.erb

$('.complete-link-single').html('<%= complete_link_text(@lesson.progress(current_user)) %>');

【问题讨论】:

  • 您的 JQuery 引用了complete-link-single,但您的link_to 中有complete_link_single(下划线)。
  • 啊,谢谢你,但问题仍然存在。

标签: jquery ruby-on-rails ajax


【解决方案1】:

未测试,但您可能需要像这样添加咖啡脚本代码:

$ ->
  $(".complete-link-single").on "ajax:success", (e, data, status, xhr) ->
   $('.abc').text('Un-complete')

假设您的链接有一个像这样的“abc”类

<%= link_to 'Complete', create_progress_lesson_path, :method => 'post', remote: true, :class=>'abc' %>

来源:http://guides.rubyonrails.org/working_with_javascript_in_rails.html#link-to

【讨论】:

  • 感谢您的回复,仍然无法正常工作,但我会通过指南链接阅读。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-29
  • 1970-01-01
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
相关资源
最近更新 更多