简体   繁体   中英

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 Javascript.

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].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM