简体   繁体   中英

How to pass json data from ruby controller to javascript (Rails 6.1)?

I'm trying to pass some json data from my database to front-end so that I can manipulate those with javascript! I started by creating some temporary json data in my home.html.erb as follows:

<%= javascript_tag do %>
    window.testJSON_data = 
    [
        {
            "name" : "Bill Gates",
            "telephone" : 123456789
        },
        {
            "name" : "Elon Musk",
            "telephone" : 987654321
        }
    ];
    console.log(testJSON_data); /* Works as expected - will print JSON data in console! */
<% end %>

The code above will print the correct data and JSON format on the console log. But I find some issues while I try to use my database data with the same approach. I started by passing the correct data to my home controller. The ruby code in the controller below will print all data on the browser page using the render function, but obviously that's not what I want to do. So I commented the render command and tried to capture these data with my home.html.erb

class HomeController < ApplicationController
  def index
    @data = EmergencyFriend.all
    @jsonData = JSON.pretty_generate(@data.as_json)

    #render json: @jsonData
  end
end

I have tried this code which almost prints the data as I want but not as an object. I have also tried these, but none will print data as object:

  • console.log(JSON.stringify('<%= j @jsonData.as_json.html_safe %>'));
  • console.log(JSON.stringify('<%= j @jsonData.as_json %>'));
  • console.log(JSON.stringify('<%= j @jsonData %>'));
<%= javascript_tag do %>
    console.log('<%= j @jsonData %>');
<% end %>

WILL RETURN:

[
  {
    &quot;id&quot;: 1,
    &quot;first_name&quot;: &quot;Emergency Contact&quot;,
    &quot;last_name&quot;: &quot;01&quot;,
    &quot;phone_number&quot;: 150431,
    &quot;email&quot;: &quot;user_01@email.com&quot;,
    &quot;twitter&quot;: &quot;@user01&quot;,
    &quot;created_at&quot;: &quot;2021-06-08T12:20:46.298Z&quot;,
    &quot;updated_at&quot;: &quot;2021-06-08T13:04:28.480Z&quot;,
    &quot;user_id&quot;: 1,
    &quot;country_code&quot;: &quot;CY&quot;,
    &quot;dial_code&quot;: 357
  },
  {
    ...
  },
  {
    ...
  }
]

I know is something stupid but I have been trying for an hour to find a solution and I cannot, It's either passing the data wrongly or printing the data wrongly. but I do not know which is the case here.

What should I do to store JSON data from ruby controller to JavaScript?

Use html_safe or raw method on that string.

<%= @jsonData.to_s.html_safe %>

Consider also fetching it by ajax request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM