· 1 min read

Screencast: Daten an JavaScript übergeben

Downloads in verschiedenen Formaten:

mp4 m4v webm ogg

Resourcen:

products/index.html.erb

[html] <%= javascript_tag do %> window.productsURL = ”<%=j products_url %>”; window.products = <%=raw Product.limit(10).to_json %>; <% end %> [/html]

app/assets/javascripts/products.js.coffee

[javascript] jQuery -> alert productsURL [/javascript]

products/index.html.erb

[html] <%= content_tag “div”, id: “products”, data: {products: Product.limit(10)} do %> Loading products… <% end %> [/html]

app/assets/javascripts/products.js.coffee

[javascript] jQuery -> alert $(‘#products’).data(‘products’) [/javascript]

Gemfile

[ruby] gem ‘gon’ [/ruby]

layouts/application.html.erb

[html] <%= include_gon %> [/html]

products_controller.rb

[ruby] def index gon.products = Product.limit(10) # or gon.rabl “app/views/products/index.json.rabl”, as: “products” end [/ruby]

products/index.json.rabl

[javascript] collection Product.limit(10)

attributes :id, :name, :price [/javascript]

app/assets/javascripts/products.js.coffee

[javascript] alert gon.products if gon [/javascript]

Back to Blog