在我的Rails应用程序中,当他查看某个帖子时,我会将某个用户添加到阅读器列表中。
PostsController#显示
@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请求发布。任何帮助将不胜感激。
答案 0 :(得分:1)
这一行:
# 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不应该是新操作的答案,但必须位于触发创建新读者链接事件的页面中。
如果您不知道自己在做什么,我建议您阅读@FlufflyJack在您的问题中评论过的链接