开发者

AJAX with Ruby on Rails?

This is probably a really dumb question with a simple answer but...

I am working on a project where I need to use AJAX to send/receive information. I am using Ruby on Rails (which I am pretty new to), but rather than using the helper methods or the built in functionality in the 'defaults' Javascript file, I need to do this manually in my own Ja开发者_运维百科vascript.

I believe that ultimately I will want to send a request with a JSON object, then have the controller return another JSON object containing the requested information.

The problem is that I cannot seem to find the syntax for sending something to a specific controller method, with parameters, directly from Javascript - everything I Google ends up being tutorials for using the Rails AJAX helper methods.


Depending on the version of Rails you're using, you can do the following:

  1. Install the jrails plugin. This will replace all the Prototype javascript in your application with jQuery. This means you now have access to all the jQuery libraries, but it won't break your existing rails helper stuff (remote_form_for, etc).

  2. Now you can use the jQuery AJAX to make any AJAX requests you want to make. A simple example would be something like below:

    //Let's get a specific post by id
    $.ajax({
        type: "GET",
        url: "/posts/123",
        success: function(data){
            //put the data in the DOM
        }
    });
    

Then just add the appropriate respond_to in your controller:

PostsController < ApplicationController
  def show
    @post = Post.find(params[:id)
    respond_to do |w|
      w.json { render :json => @post.to_json }
    end
  end
end


if using jQuery is an option for you, jQuery.ajax will solve your problem.

[and for those who likes to say jQuery is not solution for everything, i know that. i'm just giving him an option].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜