简体   繁体   English

Rails:如何将数据从Ruby传递到Javascript

[英]Rails: how to pass data from Ruby to Javascript

I am using Rails 4. In one of my controllers, I make a call using HTTParty to get data from the last_fm API - The user specifies a city, and then I have constructed an html page so that the details of upcoming concerts in that city are displayed in a table (title, date, artists, etc). 我正在使用Rails4。在我的一个控制器中,我使用HTTParty进行调用以从last_fm API中获取数据-用户指定了一个城市,然后我构建了一个html页面,以便该城市即将举行的音乐会的详细信息在表格中显示(标题,日期,艺术家等)。

The next goal of my app is to map these concerts using the Google Maps API. 我的应用程序的下一个目标是使用Google Maps API映射这些音乐会。 I have managed to load up a map on the page and have the "city" parameter (specified by the user's search) be the location that the map automatically centers at. 我设法在页面上加载了地图,并将“ city”参数(由用户的搜索指定)作为地图自动居中的位置。

Since I got the Last_fm data through a Ruby HTTP method, I had to pass it to the Javascript map API code by using jQuery selectors to snatch up data from the html page. 由于我是通过Ruby HTTP方法获取Last_fm数据的,因此我不得不使用jQuery选择器将其传递给Javascript Map API代码,以从html页面中获取数据。 Essentially, in order to pass any data from Ruby (including parameters submitted by the user through forms and the last_fm API request/response), I need to put that code in the html (the 'view') and then use jQuery to get that data into javascript. 本质上,为了传递来自Ruby的任何数据(包括用户通过表单和last_fm API请求/响应提交的参数),我需要将该代码放入html(“视图”)中,然后使用jQuery来获取数据导入javascript。 I was fine using this method, but when I tried to write a function for passing more complex code from Ruby to Javascript, I hit a roadblock. 我使用这种方法很好,但是当我尝试编写一个将更复杂的代码从Ruby传递到Javascript的函数时,遇到了障碍。

Here is where I am stuck: There is a line in my javascript file =: console.log($("div.music_id")); 这是我遇到的问题:我的javascript文件中有一行=: console.log($("div.music_id")); I also tried console.log($("div.music_id").contents()); 我也尝试过console.log($("div.music_id").contents()); Both simply printed to the console [object Object] . 两者都简单地打印到控制台[object Object] I am not sure why this is the case. 我不知道为什么会这样。 I have many div.music_id elements on the page and I need to iterate through them in order to capture information from their child DOM nodes. 我的页面上有很多div.music_id元素,我需要遍历它们以便从其子DOM节点捕获信息。 I am not able to iterate through them because jQuery does not appear to be capturing the element as I hoped it would. 我无法遍历它们,因为jQuery似乎并没有像我希望的那样捕获元素。 I was hoping that it would produce an array of objects that I could then perform further jQuery selector methods on to refine my selection, but I am unable to do this. 我希望它会产生一组对象,然后可以对它们执行进一步的jQuery选择器方法以优化选择,但是我无法做到这一点。 Thanks for your help. 谢谢你的帮助。 By the way, the code in my 'view' is here (note that it has embedded ruby): 顺便说一句,我的“视图”中的代码在这里(请注意,它已嵌入红宝石):

<h1>Show data for city specified on previous page</h1>
  <% @events.each do |x| %>
  <div class="music_id" id=<%= x["id"] %>>
    <div class="venue">
      <h3>Event Venue:</h3>
      <p><%= x["venue"]["name"] %></p>
    </div>
    <div class="time">
      <h3>Date & Time:</h3>
      <p> <%= x["startDate"] %></p>
    </div>
    <div class="event_title">
      <h3>Title:</h3>
      <p> <%= x["title"] %></p>
    </div>
    <div class="artists_playing">
      <h3>Artists playing:</h3>
      <% array = Array(x["artists"]["artist"]) %>
      <% array.each do |y| %>
        <%= array.index(y) + 1 %>)
        <%= y %>
        <br>
      <% end %>
    </div>
    <hr> 
  </div>
<% end %>

and @events refers to this code found in the controller (Ruby code): @events引用在控制器中找到的以下代码(Ruby代码):

@event_list = self.class.get(' http://ws.audioscrobbler.com/2.0/ ', :query => { @event_list = self.class.get(' http://ws.audioscrobbler.com/2.0/',:query => {

:method => 'geo.getEvents',
:location => params[:city],
:format => 'json',
:api_key => 'xxxxxxyyyyyyzzzzz'})
@events = @event_list["events"]["event"]

This Ruby code inherits methods from HTTParty, which I require at the top of the controller. 这段Ruby代码继承了HTTParty的方法,我在控制器顶部需要它。 The view code presents the data fine, so the problem is that I unable to move it to the Javascript file. 视图代码可以很好地显示数据,因此问题是我无法将其移至Javascript文件。

I am hoping for some advice regarding if there is a better way to pass info from Ruby to Javascript, or how I should do it. 我希望就是否有更好的方法将信息从Ruby传递到Javascript或应该如何做提供一些建议。 Thanks 谢谢

I think your problem is that you should use json with arrays. 我认为您的问题是您应该将json与数组一起使用。 Try to use array.to_json . 尝试使用array.to_json How can I use JavaScript to parse Ruby JSON string 如何使用JavaScript解析Ruby JSON字符串

Once converted to json, it should be iterable. 一旦转换为json,它应该是可迭代的。

Try using the gon gem. 尝试使用gon宝石。 Ryan bates shows how to use this and gives other options on passing ruby objects to javascript: 瑞安·贝茨(Ryan bates)显示了如何使用此方法,并提供了将红宝石对象传递给javascript的其他选项:

http://railscasts.com/episodes/324-passing-data-to-javascript http://railscasts.com/episodes/324-passing-data-to-javascript

By the way, have you tried to use inspect element to make sure that the ids inserted to the elements are correct? 顺便说一句,您是否尝试过使用inspect元素来确保插入到元素中的id是正确的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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