Ant*_*ony 9 javascript ajax jquery ruby-on-rails
**编辑这篇文章是因为我发现问题实际上是无法将rails绑定到ajax:success函数.
***使用rails 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.
Run Code Online (Sandbox Code Playgroud)
在此之后,我想在用户添加内容时使用不显眼的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();
});
Run Code Online (Sandbox Code Playgroud)
如果我将其更改为绑定到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();
});
Run Code Online (Sandbox Code Playgroud)
所以必须要绑定到ajax:在创建项目后成功.你们知道为什么会这样吗?我是否需要在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
Run Code Online (Sandbox Code Playgroud)
小智 18
问题听起来像绑定在元素生成之前发生.试试这个:
$(document).on('ajax:success', '.delete', function(e) {
$(e.currentTarget).closest('div').fadeOut();
});
Run Code Online (Sandbox Code Playgroud)
小智 12
我遇到了同样的问题,因为我的表单处理程序方法返回了一个纯字符串.一定要呈现jQuery可以处理的东西:
def handle_form
...
render :json => {:what => 'ever'}
# or
render :nothing => true
end
Run Code Online (Sandbox Code Playgroud)