如何使用内联:确认选项的html帮助与AJAX调用? [英] How to use inline :confirm option for html helpers with AJAX calls?

查看:296
本文介绍了如何使用内联:确认选项的html帮助与AJAX调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图有一个AJAX实现记录删除与按钮相关联。问题是在这种情况下似乎没有触发ajax:success 事件。

I am trying to have an AJAX implementation of record deletion associated with a button. The problem is that ajax:success event doesn't seem to be triggered in such case.

我已经实现了从这篇文章的建议: Rails:confirm modifier callback?)但我不确定是否是首选方式。

I have implemented the suggestion from this post: Rails :confirm modifier callback?) but I am uncertain if it's the preferred way.

我想知道如果共同的智慧在这种情况下可以帮助。这里有什么正确的方法?

I was wondering if communal wisdom could help in this case. What's the right approach here?

%td= button_to 'Delete', contender, remote: true, method: :delete, class: 'delete_contender', confirm: 'Are you sure?' if owns?



app / assets / javascripts / competitions.js:


$ b $ ('confirm:complete',function(e,res)'); b。

app/assets/javascripts/competitions.js:

$(document).ready(function() {
  $('.delete_contender').on('confirm:complete', function(e, res) {
    if (res) {
      $(e.currentTarget).closest('tr').fadeOut();
    }
  });
});



app / controllers / contenders_controller.rb:



app/controllers/contenders_controller.rb:

def destroy
  @contender = Contender.find(params[:id])
  @competition = @contender.competition
  @contender.destroy

  respond_to do |format|
    format.js   
    format.html { redirect_to @competition, notice: "Contender #{@contender.sn_name} has been deleted" }
    format.json { head :no_content }
  end
end


推荐答案

:这不是正确的方法。

The quick answer is: that is not the right approach. The long answer is below.

而不是使用.delete_contender类作为动作绑定的锚,我应该使用form [data-remote],因为* button_to *帮助器生成表单。此外,没有必要将JS钩子保留在资产管道中,最好将其移动到视图并转换为CoffeeScript。 Rails 3样式解决方案是:

Instead of using .delete_contender class as an anchor for action binding, I should have used "form[data-remote]" since *button_to* helper generates a form. Also, there is no need to keep the JS hook inside the asset pipeline, it's better to move it to the views and convert to CoffeeScript. The Rails 3 style solution is:

%td= button_to 'Delete', contender, remote: true, method: :delete, confirm: 'Are you sure?' if owns?



app / views / competitions / destroy.js.coffee:



app/views/competitions/destroy.js.coffee:

jQuery ->
  $("form[data-remote]").on "ajax:success", (e, data, status, xhr) ->
    $(e.currentTarget).closest('tr').fadeOut()



app / controllers / contenders_controller.rb:



app/controllers/contenders_controller.rb:

respond_to :js, only: :destroy

def destroy
  @contender = Contender.find(params[:id])
  @competition = @contender.competition
  @contender.destroy
end

这篇关于如何使用内联:确认选项的html帮助与AJAX调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆