【问题标题】:Callback after Rails link with data-remote="true" and data-method="PUT"Rails 与 data-remote="true" 和 data-method="PUT" 链接后的回调
【发布时间】:2013-08-19 15:17:37
【问题描述】:

我有这个红宝石代码:

link_to t("general.actions.#{ action }"), [action, @app, item], { 
   :method => :put, 
   :remote => true, 
   :onclick => '$(this).closest("tr").find("td").fadeOut()' 
}, :class => 'status' 

生成这个 html:

<a href="/apps/guess-the-model/contents/52118140d644363dc4000005/approve" 
   data-method="put" 
   data-remote="true" 
   onclick="$(this).closest("tr").find("td").fadeOut()" 
   rel="nofollow">
    approve
</a>

问题是,我不应该使用 onclick。只有当 AJAX 成功时我才应该调用这个 js 代码,所以我应该以某种方式传递一个回调并检查 XMLHttpRequest 状态。如何使用:remote =&gt; true:method= :put 做到这一点?

【问题讨论】:

  • 我觉得,你应该把这个js写在方法的js模板中,这个模板是被远程链接调用的。

标签: ruby-on-rails ajax callback link-to link-to-remote


【解决方案1】:

使用remote: true,Rails 以js 格式对您的控制器操作进行ajax 调用。因此,当您准备好呈现输出时,在控制器的操作中,您只需指定format.js 选项,如下所示:

def action
  ...

  respond_to do |format|
    format.html {...} # You probably have something like this already
    format.js {} # Add this line
end

然后,您需要在您的app/views/app/ 目录中添加一个action.js.erb 文件并在那里执行您想要在onclick 上执行的javascript 代码。

【讨论】:

    【解决方案2】:

    你也可以像这样在你的 javascript 中 use the 'ajax:success' hook

    jQuery

    $('a.status').on('ajax:success', function(ev) {
        $(this).closest("tr").find("td").fadeOut()
    })
    

    咖啡

    $ ->
        $("a.status").on "ajax:success", (event) ->
        //your code
    

    并删除链接的onclick 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      相关资源
      最近更新 更多