Dynamic content with ajax (ruby on rails)

I use Rails and jquery and I need dynamic content with ajax.

But I do not know how to get the current user id

For example, URL: www.mywebsite.com/users/ 20

In my javascript file I need user id (20)

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

      }, "json");

Thanks in advance for your help.


Is there any other way to do this?

+5
source share
5 answers

You can assign the value of the rails variable to the javascript variable in your view file, e.g.

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

and access to the variable inside the js file wherever you want.

+4
source

hidden id - , $("#user_id") javascript, :

var id = $("#user_id").val();
$.get("/users/"+id+".json", function(data) { }, "json");
+5
$.get("/users/<%= params[:id] %>.json", function(data)
  {

  }, "json");

.

.erb .js.erb .

+2

:

  • (: , .js.erb):

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

  • .js.erb, , - , .

  • id URL- ( URL-, www.mywebsite.com/users/20, , GET- 20 ), document.url window.location.href , .

+1
source

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

0
source

All Articles