Rails 3: How to make an Ajax call?

前端 未结 2 1061
北恋
北恋 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:53

    You're really going to be using two technologies to accomplish this: javascript on the client-side, and rails on the server-side.

    The general idea is that you want to:

    (1) add your web methods on the server side with rails, and then
    (2) use something like jQuery to get your client-side js calls up to the server to fire off the web methods.

    Two writeups I found by googling for : rails3 ajax

    http://www.stjhimy.com/posts/7-creating-a-100-ajax-crud-using-rails-3-and-unobtrusive-javascript

    http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/

    API Reference for using jQuery's ajax post() method:
    http://api.jquery.com/jQuery.post/

    0 讨论(0)
  • 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')"
    
    0 讨论(0)
提交回复
热议问题