且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Ajax/jQuery进行更新操作而无需重新加载页面

更新时间:2023-02-11 18:46:16

您使用的是jQuery吗?将click事件绑定到您想要触发更新的任何元素.例如:

Are you using jQuery? Bind a click event to whatever element you'd like to trigger an update. For example:

在您的路线上:

resources :users do
  collection do
    post "rsvp_to_event"
  end
end

在您的控制器中:

def rsvp_to_event
  user_id = params[:user_id]
  rsvp_id = params[:rsvp_id]

  # do what you need to do

  # then render json and send back whatever you need

  render json: {data: "Success"}
end

您认为:

<button class="some-class" data-user-id="<%= current_user.id %>">Example</button>

<script>
   $(document).on('ready', function(){
     $('.some-class').on('click', function(e){
     // this keeps page from reloading
     e.preventDefault()

     $.ajax({
       type: 'POST',
       url: '/controller_action_you_want_to_post_to',
       data: { user_id: $('.some-class').data('user-id') }
     }).done(function(response){ console.log('response', response })
     // you can update the page in the done callback
     // update your data in the controller action you're posting to
    }
   })
</script>