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.com/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 ?
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:
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");
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.
If you have the id value in the url (as in the current url you are on looks like www.mywebsite.com/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.
尝试<%= escape_javascript(params [:id])%>我不完全确定escape_javascript是否必要或将有所帮助。
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.