【问题标题】:Rails 3.2.8 not firing ajax callbacksRails 3.2.8 不触发 ajax 回调
【发布时间】:2012-09-06 23:40:52
【问题描述】:

我在使用 rails 3.2.8 和 ajax 回调时遇到问题...似乎这些都没有触发...我尝试使用 Jquery 代码绑定(我可以在 chrome 工具箱上看到 js 脚本)我什至尝试将 :success => 'alert("bla")' 放在 link_to 行上,但它仍然没有做任何事情......控制器工作,因为我的行实际上已被删除......但可以'不绑定到回调!请帮忙!

这是我的观点:

<td><%= link_to 'Destroy', pet, :method => :delete, :remote=>true, :class => 'delete_pet' %></td>

这是我的控制器操作

def destroy
    @pet = Pet.find(params[:id])
    @pet.destroy

    respond_to do |format|
      format.html { redirect_to(pets_url) }
      format.js { render :nothing => true }
    end
  end

这是我的js代码:

jQuery(function($) {
    $('.delete_pet').bind("ajax:before", function(){alert('bla2');})
                    .bind("ajax:success", function(){alert('bla2');})
                    .bind("ajax:failure", function(){alert('bla2');})
                    .bind("ajax:complete", function(){alert('bla2');});
});

【问题讨论】:

  • 确保源中没有包含冲突的 jQUery。检查浏览器控制台是否有任何输出。
  • 天才!这就是问题所在!在我的一次尝试中......我在我的application.js中手动包含了jquery js文件......没有错误......但这似乎与rails jquery冲突!谢谢!

标签: ruby-on-rails ruby ajax ruby-on-rails-3 callback


【解决方案1】:

替换

 format.js { render :nothing => true }

 format.json { render :nothing => true }

也替换

<%= link_to 'Destroy', pet, :method => :delete, :remote=>true, :class => 'delete_pet' %>

<%= link_to 'Destroy', pet, :method => :delete, :remote=>true, 'data-type'=>'json', :class => 'delete_pet' %>

【讨论】:

  • 我这样做了,但现在.. 在 chrome 工具箱上“我收到此错误 GET localhost:3000/pets 404 (Not Found)”
  • 感谢 Emrah,但这并没有解决问题......现在它什么也没做......没有错误,就像在开始时一样。
【解决方案2】:

respond_to 块我也遇到过类似的问题。我通过检查request 暂时解决了这个问题。例如,您的代码如下所示:

def destroy
  @pet = Pet.find(params[:id])
  @pet.destroy

  if request.xhr? 
    # the request was received via an AJAX request
    render :nothing => true
  else
    redirect_to(pets_url)
  end
end

不像resond_to 块那么优雅,但它似乎可以按预期可靠地工作。

祝你好运!

【讨论】:

  • 不,它也不起作用..但我的项目可能有问题..我的意思是,不是事件 ajax:before 回调没有触发..不应该在之前触发ajax 调用?
【解决方案3】:

问题在于,在我的 application.js 上,我手动包含了一个 jquery 文件......就像这样......

//= require jquery-ui-1.8.23.custom

真丢脸!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多