[英]dynamic content with ajax (ruby on rails)
I am using Rails and jquery, and I need a dynamic content with ajax. 我正在使用Rails和jquery,我需要一个带有ajax的动态内容。
But I don't know how to get the current user ID 但我不知道如何获取当前的用户ID
For example the url is www.mywebsite.com/users/ 20 例如,网址是www.mywebsite.com/users/ 20
In my javascript file I need the user ID (20) 在我的javascript文件中,我需要用户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: 通常我在页面的某处放置一个带有
id
的hidden
字段,我可以在javascript文件上使用$("#user_id")
轻松访问,然后请求将是这样的:
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 您可以将rails变量值分配给视图文件中的javascript变量,如
"<%= javascript_tag "var userId = #{@current_user.id};" %>"
“<%= javascript_tag”var userId = #{@current_user.id};“%>”
and access the variable inside js file wherever you want. 并在任何地方访问js文件中的变量。
$.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. 将代码段包含到.erb文件中或使用此文件创建.js.erb部分。
Lots of choices: 很多选择:
If you have a current user object with the id ( Note : this must be in a file ending with .js.erb
): 如果您有一个具有id的当前用户对象( 注意 :这必须位于以
.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. 如果您不想使用
.js.erb
文件,但仍需要在页面的某处设置值,则使用id值设置数据属性或隐藏输入。
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. 如果你在url中有id值(就像你当前的url看起来像
www.mywebsite.com/users/20
并且你希望GET请求使用20作为值),你可以使用document.url
或者window.location.href
和一些字符串操作来获取id。
尝试<%= escape_javascript(params [:id])%>我不完全确定escape_javascript是否必要或将有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.