问题描述
我正在尝试构建一个非常简单的页面,我需要在其中为照片库生成一些动态 JavaScript.一些直觉上很简单的东西,但我正在为此苦苦挣扎.在我的控制器中,我将 Photo
列表构建为 @photos
,然后需要为我的 photo.js.erb中的每张照片迭代一些 JavaScript代码>文件.
I'm trying to build a really simple page, where I need to generate some dynamic JavaScript for a photo gallery. Something intuitively simple, but which I'm struggling with greatly. In my controller I am building a list of Photo
as @photos
, then need to iterate out some JavaScript for each photo in my photo.js.erb
file.
然而,每当我到达我的 .js.erb 文件时,@photos
变量就会变成 nil ......我错过了什么?
However, whenever I reach my .js.erb file, the @photos
variable becomes nil... what am I missing?
controllers/photos_controller.rb 文件:
class PhotosController < ApplicationController
layout "application_photos"
def category
@photos = ...(generates collection of Photos)...
end
end
views/photos/category.html.haml 文件:
= content_for :head do
// @photos is still initialized at this point
= javascript_include_tag "photos"
// This partial only loads some more markup, it's inconsequential.
= render :partial => 'default_slideshow'
javascripts/photos.js.erb 文件:
jQuery(function($){
// Throws NilClass error
<% puts 'Photos: ' + @photos %>
});
我知道这个问题已经被问过十几次了,但以前接受的答案都没有对我有用.非常感谢任何建议.
I know this question has been asked a dozen times, but none of the previously accepted answers actually worked for me. Any suggestions are greatly appreciated.
推荐答案
您需要向服务器发送 js 请求才能访问实例变量.像这样
You need to send js request to the server in order to have access to the instance variable. Something like this
$(function($){
$.ajax({
type: "get",
url: "..."
})
});
在 views/photos/category.js.erb 文件中:
In views/photos/category.js.erb file:
alert("<%= j @photos %>")
或者您可以使用 gon gem 执行相同操作.
Or you can do the same using gon gem.
app/views/layouts/application.html.erb
<head>
<title>some title</title>
<%= include_gon %>
<!-- include your action js code -->
...
你在控制器的动作中加入了这样的东西:
You put something like this in the action of your controller:
@your_int = 123
@your_array = [1,2]
@your_hash = {'a' => 1, 'b' => 2}
gon.your_int = @your_int
gon.your_other_int = 345 + gon.your_int
gon.your_array = @your_array
gon.your_array << gon.your_int
gon.your_hash = @your_hash
gon.all_variables # > {:your_int => 123, :your_other_int => 468, :your_array => [1, 2, 123], :your_hash => {'a' => 1, 'b' => 2}}
gon.your_array # > [1, 2, 123]
gon.clear # gon.all_variables now is {}
从您的 JavaScript 文件访问变量:
Access the varaibles from your JavaScript file:
alert(gon.your_int)
alert(gon.your_other_int)
alert(gon.your_array)
alert(gon.your_hash)
希望能帮到你
这篇关于Rails 3:在 .js.erb 文件中无法访问实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!