Rails 3: How to make an Ajax call?

前端 未结 2 1079
北恋
北恋 2020-12-30 06:35

I would like to have a link (is there a better option?) on my page which will make an Ajax request when clicked. (I would like to update a field in my database when the link

2条回答
  •  一向
    一向 (楼主)
    2020-12-30 06:56

    Really simple. In your view, have a link/button like so. Important bit being :remote => true

    <%= link_to 'Update Thingy', update_thingy_path, :confirm => 'You sure you wanna update?', :remote => true %>
    

    or

    <%= button_to('Update Thingy', {:action => 'update_thingy', :thingyid => 314}, :method => :get, :remote => true) %>
    

    Obviously, you have to get update_thingy_path to resolve to some action as normal. The difference is when you render you are going to be rendering some *.js.erb instead of *.html.erb. In that update_thingy.js.erb, you just put whatever javascript you want to run in the client. You might wanna notify the user that the update happened for example (in jQuery):

    $('#notice').html("Thingy was update.")
    

    Or if whatever javascript you're returning is really simple, in the controller you can do something like the following instead of having a whole js.erb for a one-liner.

    render :js => "alert('Blah')"
    

提交回复
热议问题