admin管理员组

文章数量:1291335

I am using Rails and jquery, and I need a dynamic content with ajax.

But I don't know how to get the current user ID

For example the url is www.mywebsite/users/20

In my javascript file I need the user ID (20)

$.get("/users/<%= **20** %>.json", function(data)
      {

      }, "json");

Thanks in advance for any help.


Is there another way to do this ?

I am using Rails and jquery, and I need a dynamic content with ajax.

But I don't know how to get the current user ID

For example the url is www.mywebsite./users/20

In my javascript file I need the user ID (20)

$.get("/users/<%= **20** %>.json", function(data)
      {

      }, "json");

Thanks in advance for any help.


Is there another way to do this ?

Share Improve this question edited Jul 31, 2012 at 18:32 casperOne 74.6k19 gold badges189 silver badges260 bronze badges asked Jul 30, 2012 at 17:48 user1560922user1560922 2671 gold badge5 silver badges19 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 5

Generally i put a hidden field with the id somewhere in the page, where i can easily access with $("#user_id") on the javascript file, then the request would be something like this:

var id = $("#user_id").val();
$.get("/users/"+id+".json", function(data) { }, "json");

You can assign the rails variable value to a javascript variable in your view file like

"<%= javascript_tag "var userId = #{@current_user.id};" %>"

and access the variable inside js file wherever you want.

$.get("/users/<%= params[:id] %>.json", function(data)
  {

  }, "json");

Should do the trick.

Include the snippet into the .erb file or create a .js.erb partial with this.

Lots of choices:

  1. If you have a current user object with the id (Note: this must be in a file ending with .js.erb):

    $.get("/users/<%= @current_user.id %>.json", function(data){...}, "json");

  2. If you don't want to use a .js.erb file, but still need the value to be set somewhere on the page, then set a data-attribute or hidden input with the id value.

  3. If you have the id value in the url (as in the current url you are on looks like www.mywebsite./users/20 and you want the GET request to use 20 as the value), you can use document.url or window.location.href and some string manipulation to get the id.

Try <%= escape_javascript(params[:id]) %> I'm not pletely sure if escape_javascript is necessary or will help.

本文标签: javascriptdynamic content with ajax (ruby on rails)Stack Overflow