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 badges5 Answers
Reset to default 5Generally 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./users/20
and you want the GET request to use 20 as the value), you can usedocument.url
orwindow.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
版权声明:本文标题:javascript - dynamic content with ajax (ruby on rails) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741518271a2383026.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论