简体   繁体   中英

JavaScript doesn't like hashes.to_json?

In my controller:

@arr = []
@jsonPosts = Post.each do |p|
  arrLatLng = {}
  arrLatLng["latitude"] = p.lat
  arrLatLng["longitude"] = p.lon
  @arr << arrLatLng
end 
@postsLatLng = @arr.to_json

When I use console.log(<%= @postsLatLng %>) , in the view I get an unexpected token and error and it shows:

console.log([{&quot;latitude&quot;:34.0462002,&quot;longitude&quot;:-118.2044673},{&quot;latitude&quot;:34.0462074,&quot;longitude&quot;:-118...

It works when I change arrLatLng to an array:

arrLatLng = []
arrLatLng << p.lat
arrLatLng << p.lon

I'm wondering:

  1. What's the fix?
  2. Why does this work when I change arrLatLng to an array?

Try http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-ij

console.log(<%= j @postsLatLng %>)

Also, totally unrelated, but you could do this instead:

@postsLatLng = Post.inject([]) { |memo, p|
  memo << {latitude: p.lat, longitude: p.lon}
}.to_json

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