9

**编辑这篇文章是因为我发现问题实际上在于 rails 无法绑定到 ajax:success 函数。

***使用导轨 3.2.3

感谢您花时间阅读并尝试提供帮助。

我在ajax上添加了一个简单的淡出功能:成功删除项目,如下:

$(document).ready( jQuery(function($) {
    $('.delete').bind('ajax:success', function() {
        $(this).closest('div').fadeOut();
    });
}));
#For some reason had to pass the $ into the function to get it to work,
#not sure why this is necessary but doesn't work unless that is done.

在此之后,我想在用户添加内容时使用不显眼的 jQuery 创建一个对象,并且在这些对象上也有有效的删除按钮。我创建了一个 create.js.erb 文件,该文件在创建新项目后调用 - 并且创建工作正常,但删除按钮无法访问 ajax:success 事件。

单击时它确实会从数据库中删除数据,但 .fadeOut 从未绑定到它,因此它不会消失。create.js.erb 如下:

#$("div").append(html) here, then call the function below to try and bind the ajax:success function
$('.delete').bind('ajax:complete', function() {
    $(this).closest('div').fadeOut();
});

如果我将其更改为绑定到 click 函数,它可以工作,但这并不能说明 ajax 调用失败:

#$("div").append(html) here, then call the function below to try and bind the ajax:success function
    $('.delete').bind('click', function() {
        $(this).closest('div').fadeOut();
    });

因此,在创建项目后,必须与 ajax:success 绑定。你们知道为什么会发生这种情况吗?我是否需要在 Rails 中做一些特别的事情来让新渲染的项目识别 ajax 事件?任何方向将不胜感激!

PS删除方法的控制器如下,以防任何人在那里检测到问题:

def destroy
    @user = User.find(params[:user_id])
    @item = @user.item.find(params[:id])
    @item.destroy

    respond_to do |format|
      format.html { redirect_to user_path(@user) }
      format.json { head :no_content }
      format.js { render :nothing => true }
    end
end
4

7 回答 7

18

问题听起来像是在生成元素之前发生了绑定。尝试这个:

$(document).on('ajax:success', '.delete', function(e) {
    $(e.currentTarget).closest('div').fadeOut();
});
于 2012-08-31T19:19:07.043 回答
12

我遇到了同样的问题,因为我的表单处理程序方法返回了一个纯字符串。一定要渲染一些 jQuery 可以处理的东西:

def handle_form
  ...
  render :json => {:what => 'ever'}
  # or
  render :nothing => true
end
于 2012-11-07T11:46:05.533 回答
1

尽管这是一个老问题,但我有一个更新的答案来解决同样的问题。

从 1.9 版开始,jQuery 将不再将空响应(render nothing: true)视为成功/完成。这意味着在您的控制器中,您应该返回一个空的 JSON 对象。

respond_to do |format| format.json { render: {}.to_json } end

于 2014-09-15T19:38:29.133 回答
1

我最近使用 Rails 3.2.3 做了类似的事情。我也用

$('#dialog-form').bind('ajax:success', function() {
})

它工作正常......

于 2013-08-15T19:40:46.970 回答
0

通过 catch 检查您是否收到解析错误(或类似错误)ajax:completed。检查status那里的论点。就我而言,这是parseerror由于 mimetype 不匹配造成的。

您还可以在jquery_ujs.js.

另请参阅此问题jQuery ajax request not triggering JS response

于 2014-04-29T23:02:41.670 回答
0

对我来说,这是因为我们使用的是 slim,模板是“name.slim”。如果我们将它们更改为“name.slim.html”,则 ajax:success 会正确触发。

我正在使用的解决方案是将格式添加到控制器中的渲染声明中。

所以我们有这样的东西:

render :new, layout: false, formats: [:html]
于 2015-10-16T18:11:38.423 回答
0

即使这是一个老问题,没有一个答案真的对我有帮助,因为我有一个自定义确认对话框,并且 ajax:success 触发了完全不同的元素。

为了找到在这种情况下您的 ajax 触发了哪个元素,您可以首先使用代码:

$(document).on('ajax:success', 'a', function(evt, data, status, xhr) {
    $( ".log" ).text( "Triggered ajaxComplete handler." );
    // Check what is the value of $(this), and you will see what button has triggered the ajax success action, and you can start from there
});
于 2016-09-12T23:38:31.320 回答