将ajax请求绑定到特定元素Rails 3.1

编程入门 行业动态 更新时间:2024-10-27 20:36:52
本文介绍了将ajax请求绑定到特定元素Rails 3.1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个用户列表,每个用户的名字旁边都有一个关注按钮。 'follow'请求通过ajax完成,然后按下按钮变为'unfollow'按钮。

I have a list of users who each have a 'follow' button next to their name. The 'follow' request is complete via ajax and the follow button then changes to a 'unfollow' button.

我的代码在列出一个用户的情况下工作正常(并且还有后端工作,列出了多个用户)但我想要的是列出多个用户,然后以某种方式绑定按照每个按钮所包含的特定元素'.follow_form'的请求,以便只有一个孩子'关注'按钮被点击更改为'取消关注'。

My code works fine with one user listed (and also works back-end with multiple users listed) but what I would like is to list multiple users and then somehow bind the follow request to the specific element, '.follow_form' which each button is contained in, so that only the one child 'follow' button which is clicked changes to the 'unfollow'.

我遇到绑定问题的jquery代码如下:

The jquery code which I'm having trouble binding is as follows:

/create.js.erb $(".follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")

/destroy.js.erb $(".follow_form").html("<%= escape_javascript(render('users/follow')) %>")

提交表单时,显然所有.follow_form元素都已更改,但我无法弄清楚如何绑定正确的元素?

When the form is submitted obviously all the .follow_form element are changed but I can't work out how to bind the correct element?

其中一件我试过的代码(对于create.js.erb)是:

One of a few pieces of code I tried (for create.js.erb) was:

$("input.follow").bind( function() { $(this).closest(".follow_form").html("<%= escape_javascript(render('users/unfollow')) %>") });

但没有回复???

推荐答案

您可能应该在 ajax:success 回调中执行此操作,因为它会自动绑定到对象。

You should probably be doing this in an ajax:success callback instead since it is automatically bound to the object.

你可以删除那些 .js.erb 文件,只需在控制器中渲染它们:

You can delete those .js.erb files and just render them in the controller:

def create # creation code here # now render the response render :json => { :new_button => render_to_string( :partial => 'users/unfollow' ) }, :status => :created end def destroy # deletion code here # now render the response render :json => { :new_button => render_to_string( :partial => 'users/follow' ) }, :status => :no_content end

然后在你的javascript文件中:

Then in your javascript file:

$('input.follow, input.unfollow').live('ajax:success', function(data, json, response) { $(this).closest(".follow_form").html(json.new_button); }); $('input.follow, input.unfollow').live('ajax:error', function(data, xhr, response) { // handle the ajax error here });

更多推荐

将ajax请求绑定到特定元素Rails 3.1

本文发布于:2023-10-11 04:34:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1480698.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   元素   ajax   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!