Rails uses Ruby objects in Javascript

Source: Internet
Author: User
1. Use a ruby simple object in Javascript. For example, convert a ruby object to a simple JavaScript variable:
<%= javascript_tag do %>  url = '<%= j products_url %>';<% end %>

<% = %> Is enclosed by quotation marks. RailsJThe method is to correctly define the ruby object and embed it into JavaScript.
2. Using Ruby complex objects in Javascript is obviously JSON, but to correctly convert JSON, you needRawMethod:

<%= javascript_tag do %>  products = <%= raw Product.limit(10).to_json %><% end %>

In this case, no quotation marks are enclosed. 3. If Gon gem has a large number of Ruby objects that need to be used in Javascript, this method is not good. GON is designed to solve this problem. First, add GON in gemfile:

gem 'gon'

Then GON is included in the/APP/views/layouts/application.html. ERB file:

Then, in controller, you can assign values to JavaScript objects in this form:

gon.variable_name = variable_value# or new syntaxgon.push({  :user_id => 1,  :user_role => "admin"})gon.push(any_object) # any_object with respond_to? :each_pair

For example:
How to Get variables in JS:

gon.variable_name

That is:

go.products
References 1. gon2.passing data to Javascript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.