[英]Render JSON from Rails controller into html script view partial
在我看來,我想創建一個與我的ruby對象current_user
匹配的javascript對象
似乎是一個不錯的解決方案,而不是向/users/me
發出額外請求。
這花了我比預期更長的時間:
<script>
window.current_user = <%= raw(current_user.to_json) %>;
</script>
從控制器發送json以查看
def show_user_categories
@categories= current_users.categories.map do |c|
{ :id => c.id,:name => c.title}
end
respond_to do |format|
format.html
format.json { render :json => @categories}
end
end
在視圖中獲取json
<%= javascript_tag do%>
window.categories= <%=raw @categories.to_json %>;
<%end%>
然后在js腳本中使用它
var markers=[];
$.each(categories, function(index) {
//creating js array which can be used in js script
//using the id/title passed from controller code
markers.push([categories[index]['id'],categories[index]['title']]);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.