【问题标题】:Implementing logic from controller with javascript and ajax request使用 javascript 和 ajax 请求从控制器实现逻辑
【发布时间】:2013-04-14 01:36:52
【问题描述】:

在我的 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 请求发布。任何帮助将不胜感激。

【问题讨论】:

标签: javascript ruby-on-rails ajax


【解决方案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 在您的问题中评论的链接

【讨论】:

  • 谢谢!这对我帮助很大!通过处理这个例子,我也比以前更好地理解了不显眼的 ajax 请求
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-26
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 2019-11-09
相关资源
最近更新 更多