使用javascript和ajax请求实现控制器逻辑

使用javascript和ajax请求实现控制器逻辑,javascript,ruby-on-rails,ajax,Javascript,Ruby On Rails,Ajax,在我的Rails应用程序中,当某个用户查看某篇文章时,我会将他添加到读者列表中 PostsController#Show @post = Post.find(params[:id]) if (current_user) @post.reader_links.create(reader_id: current_user.id) end 但是,我希望使用javascript和ajax请求从客户端实现这一点。该功能将稍有更改,因此只有当用户键入某个表单(按键)时,才会将其添加到列表中。 因此,原

在我的Rails应用程序中,当某个用户查看某篇文章时,我会将他添加到读者列表中

PostsController#Show

@post = Post.find(params[:id])
if (current_user)
  @post.reader_links.create(reader_id: current_user.id)
end
但是,我希望使用javascript和ajax请求从客户端实现这一点。该功能将稍有更改,因此只有当用户键入某个表单(按键)时,才会将其添加到列表中。

因此,原始代码将被posts/show.erb.html中的以下代码替换

function typeCatch(){
  $(this).off("keypress",typeCatch)//remove handler
  //I WANT TO ADD THE USER TO THE LIST AT THIS POINT
}

$("#field_id").on("keypress",typeCatch)

我需要一些帮助来实现javascript中的原始功能,并通过ajax请求发布。任何帮助都将不胜感激。

以下内容:

# on a controller
def update_links
  @post = Post.find(params[:id])
  if (current_user)
    @post.reader_links.create(reader_id: current_user.id)
  end
end


// on your javascript
function typeCatch(){
  $(this).off("keypress",typeCatch)//remove handler
  $.post('/path/to/controller/post_id/action')
 }

 $("#field_id").on("keypress",typeCatch)
请注意,javascript不应该是新操作的答案,但必须位于触发创建新阅读器链接事件的页面中


如果您不知道自己在做什么,我建议您阅读@fluflyjack在您的问题中评论的链接

Emm。。。在.erb文件内的javascript函数中?这会有帮助吗?还是这个?谢谢这对我帮助很大!通过处理这个例子,我也比以前更好地理解了不引人注目的ajax请求