Simple example of Rails 3 + UJS using Ajax to make a remote call, and rendering the resulting JSON object

限于喜欢 提交于 2019-11-30 05:19:29

Here is a start:

First create your button with a link_to method in your view, for example:

=link_to "delete", "#{invitation_path(invitation)}.json", :method=>:delete, :remote=>true, :class=>"remove", :confirm=>'Are you sure you?'

Note that I am appending ".json" to the url of my resource. This is just an example of a an AJAX delete, google link_to to see the meaning of the parameters. The concept if that you make your HTTP request with the parameter :remote set to true, in other words this is translated to an AJAX call from your browser.

Second, write some javascript so that you can process what ever is the result of the AJAX call your browser will make when the user click on the link_to of step 1. For details you can see this blog post: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/

An example from my site:

jQuery(function($) {
  // create a convenient toggleLoading function
  var toggleLoading = function() { $("#loading").toggle() };

  $("#pending_invitation")
    .live("ajax:loading",  toggleLoading)
    .live("ajax:complete", toggleLoading)
    .live("ajax:success", function(event, data, status, xhr) {
       var response = JSON.parse(xhr.responseText)
       if (response.result == "ok") {
          $(this).fadeOut('fast');
       }
       else {
         var errors = $('<div id="error_explanation"/>');
         errors.append('<h2>Pending invitation action error</h2><ul><li>' + response.error + '</li></ul>');
         $('#new_invitation_error').append(errors)   
       }
    });
});

where you can see that I parse the returned json and and change the html on the page based on that. Note that this js uses the CCS ids and classes defined in the top view that is not included here.

If you now want to write you own controller to spit out the json here is an example:

class InvitationsController < ApplicationController
  respond_to :html, :json

  # other methods here
  # ...

  def destroy
    @invitation = Invitation.find(params[:id])
    respond_to do |format|
      if @invitation
        @invitation.destroy
        flash[:success] = I18n.t 'invitations.destroy.success'
        format.json { render :json =>{:result => "ok", :message=>"Invitation #{params[:id]} was destroyed", :resource_id=>params[:id] } }
      else
        format.json { render :json => { :result=>"failed", :error=>"Cannot find Invitation #{params[:id]}", :resource_id=>params[:id] } }
      end
    end
  end
end

Hope this help.

Old question, but a really good overview of Ajaxifying Rails applications is:

Ajax in Rails 3.1 - A Roadmap

Also consider returning errors in the following format:

render :json => @myobject.to_json, :status => :unprocessable_entity

This will ensure that your client can process the response as an error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!