1

フォトギャラリー用に動的なJavaScriptを生成する必要がある、非常にシンプルなページを作成しようとしています。直感的にシンプルなものですが、私は非常に苦労しています。私のコントローラーでは、Photoasのリストを作成@photosしてから、ファイル内の写真ごとにJavaScriptを繰り返す必要がありphoto.js.erbます。

ただし、.js.erbファイルに到達するたびに、@photos変数はnilになります...何が欠けていますか?

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 %>
});

私はこの質問が何十回も聞かれたことを知っていますが、以前に受け入れられた答えのどれも実際には私のために働きませんでした。どんな提案でも大歓迎です。

4

1 に答える 1

3

インスタンス変数にアクセスするには、js リクエストをサーバーに送信する必要があります。このようなもの

$(function($){
  $.ajax({
    type: "get",
    url: "..."
    })  

});

views/photos/category.js.erb ファイル内:

alert("<%= j @photos %>")

または、gon gem を使用して同じことを行うこともできます。

app/views/layouts/application.html.erb

<head>
 <title>some title</title>
 <%= include_gon %>
 <!-- include your action js code -->
 ...

コントローラーのアクションに次のようなものを入れます。

@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 ファイルから変数にアクセスします。

alert(gon.your_int)
alert(gon.your_other_int)
alert(gon.your_array)
alert(gon.your_hash)

お役に立てれば

于 2013-03-04T12:56:19.477 に答える