简体   繁体   中英

Passing values between jQuery and Controller Rails

Quite a bit of links, but I can't piece all of the info together.

I assume a controller, a view and routes are involved.

Regarding the url and routes, I have the generic folder structure, app/views/pages/home and app/controllers/pages_controller.rb. Can you guide me if I'm doing the routing and url correctly, also?

routes.rb

get pages/get_aj //Don't know if this is what you put

jQuery

$.ajax({ 
type: 'get'
url: '/pages/get_aj' //can someone confirm this is how you do it? 
dataType: "JSON" //I need to pass back values from the controller to JS. Do I use JSON?
}).success(function(data){
      alert("returned " + data);
});

//some other jQuery code that will depend on the data returned.

pages_controller.rb

def get_aj
   respond_to do |format|
      format.json{render :json => "we got here" } //Do I return .js?
   end
end

rake routes

   pages_home GET /pages/home(.:format)    pages#home
pages_contact GET /pages/contact(.:format) pages#contact
 pages_get_aj GET /pages/get_aj(.:format)  pages#get_aj

Your code should work actually. The biggest thing you're misunderstanding is what JS alert does. It alerts strings, and data is an object. See this JS fiddle: http://jsfiddle.net/YNeA3/

To inspect objects from JS, use console.log() instead of alert. These will show up in your browser console. This is the basic bread and butter debugging tool for JS.

I'm not sure what the JSON object you're sending looks like, because you should be rendering a hash, not a string. That's the only real problem with your code, I think.

Also, a suggestion: if this controller action is only going to be for ajax you don't have to bother with the respond_to block. I would specify status though.

def get_aj
  data = {:message => "Alert this!"}
  render :json => data, :status => :ok
end

Now in your JS:

$.ajax({ 
  type: 'GET',
  url: '/pages/get_aj',
  success: function(data,status,xhr){
    console.log(data);
    alert(data.message);
  },
  error: function(xhr,status,error){
    console.log(xhr);
    alert(error);
  }
});

Data will be a JS object looking just like the hash you sent.

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