json,rails,javascript中的解析错误 [英] json, rails, parse error in javascript
问题描述
我需要将ruby数组放入javascript数组,并且遇到解析错误.
var characters = <%= @poop.to_json %>;
这就是我将ruby嵌入到嵌入式javascript中的方式,并提出了解析错误.我应该如何将这个ruby数组放入javascript中?
我将其嵌入到.html.erb文件中,因此ruby应该在javascript之前到达该变量.
这是野生动物园控制台显示的内容:
更新
我有一个表单,该表单分别具有js,css和html三个字段,因此我将javascript放入表单中,然后将其放入标头中.
<head>
<%= @game.javascript %>
</head>
因此,如您所见,我将ruby嵌入到ruby对象的输出中的javascript中,因此ruby未能首先到达它的原因是它已经到达并处理了<%=%>就像另一个字符串一样.
啊,我对你们的帮助投了赞成票.谢谢!
您正在将.js文件视为.erb文件,但事实并非如此. Ruby无法解析JavaScript文件-public
中的所有内容均按原样发送.
将@poop
插入JavaScript的一种方法是让Rails操作呈现json,然后使用XHR加载.
或者,您可以在HTML模板中的<script>
标签中输出@poop
,然后从JavaScript中加载该脚本标签的内容.
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 I'm embedding ruby into inline javascript and it's coming up with a parse error. How should I be getting this ruby array into javascript?
I'm embedding this into an .html.erb file so ruby should be getting to the variable before javascript.
This is what safari console is showing:
Update
I had a form that had three fields js, css, and html respectively so I would put my javascript in a form and then it would put it into the header.
<head>
<%= @game.javascript %>
</head>
So as you can see I was embedding ruby in javascript that was the output of a ruby object so the reason ruby wasn't getting to it first was that it had already got to it and treated the <%= %> just like another string.
Ahh, I up voted you all for the help. Thanks!
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.
这篇关于json,rails,javascript中的解析错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!