开发者

how to access database value with jQuery in rails application

开发者 https://www.devze.com 2023-02-17 13:42 出处:网络
I have one rails application, using omniauth. And also save token in my database. After auth process finished, I want to pull data from the omniauth provider by using jQuery, how can I 开发者_StackOve

I have one rails application, using omniauth. And also save token in my database. After auth process finished, I want to pull data from the omniauth provider by using jQuery, how can I 开发者_StackOverflowuse for example @current_user.token in my jQuery script?


With Rails 3 I recommend using js.erb template files to easily use variables in your jQuery. You set up your controller to respond to js requests, then you make a request to that URL and the rendered js.erb will execute as javascript on the browser and it can make use of the variables set by your controller action.

Your controller would look something like this:

class Users < ApplicationController
  respond_to :js, :only => :me
  def me
    @current_user = User.find(session[:user])
    respond_with(@current_user)
  end
end

Then write something like this in me.js.erb

$('#current_user_token').html("<%= escape_javascript(@current_user.token) %>");

You can call your action directly by appending .js to your URL.

http://0.0.0.0:3000/users/me.js

From a template just use a remote form or link by adding a :remote => true option

link_to "Show user token", me_users_path, :remote => true

your me.js.erb file works just like any other JS file and you can have as much JS as you want in there. use ERB tags where ever you want to use your variables or helper but make sure you wrap them in the escape_javascript helper "<%= escape_javascript(render @current_user) %>"

To just request variables with out rendering js.erb template use eggie5's suggestion and make an ajax request to an action that responds to :json. It will return your @current_user as a json object.


Since jquery is running only in the browser context it can't directly query the database which is on the server.

If you want to get access to some value from your db on the client. I would suggest either doing an AJAX call to some server endpoint or writing the value (possible as JSON) to the page and getting it w/ a jquery selector, e.g.: $('server_value')......


eggie5's idea for just grabbing JSON via AJAX is good ... another option would be to put the token in a cookie and then it's always accessible via JavaScript.

controller

class SomeController
  def some_action
    cookies[:user_token] = current_user.token
  end
end

js

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

var token = readCookie('user_token');
0

精彩评论

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