json, rails, parse error in javascript

前端 未结 3 747
不思量自难忘°
不思量自难忘° 2021-01-17 02:28

I need to get a ruby array in to a javascript array and I\'m getting a parse error.

var characters = <%= @poop.to_json %>;

That is how

相关标签:
3条回答
  • 2021-01-17 02:39
    var characters = "<%= @poop.to_json -%>";
    
    0 讨论(0)
  • 2021-01-17 02:41

    You're treating a .js file like an .erb file - it's not. JavaScript files aren't parsed by Ruby - anything in public is sent as-is.

    One way to get @poop into your JavaScript is to have a Rails action that renders json, then load that with XHR.

    Alternatively, you could output @poop in the HTML template in a <script> tag, then load the contents of that script tag from your JavaScript.

    0 讨论(0)
  • 2021-01-17 02:53

    Ideally, we need more information to properly answer, but I'm going to guess some stuff to help you...

    Assumption #1: You are using erb syntax (those "<%=" and "%>") in a .js file. These aren't parsed by Rails into anything meaningful.

    What you want to do, is use inline JS in your template or view. Javascript generation from other languages can be tricky though, use with caution.

    0 讨论(0)
提交回复
热议问题