最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I properly put embedded ruby code in to JavaScript? - Stack Overflow

programmeradmin2浏览0评论

I am trying to embed the output of Ruby code in JavaScript:

var stuff= "<% Representative.get(':4568/') %>";

The embedded part is working by itself showing a result like this:

{ "name":"John Johnson", "street":"Oslo West 555", "age":33, "phone":"555 1234567"} 

The line above is the EXACT PAGE SOURCE; it runs locally though, so I can't show you the page.

When in a variable, I try to send it to my application with this:

document.getElementById("X_Axis").value=stuff.name;

through the input:

<input type="text" id="X_Axis" />

I get a undefined value every time.

I tried hardcoding the value in the JavaScript and it works fine like that, put when the embedded Ruby is put into the JavaScript variable, it always gives me the undefined value.

I am trying to embed the output of Ruby code in JavaScript:

var stuff= "<% Representative.get('http://0.0.0.0:4568/') %>";

The embedded part is working by itself showing a result like this:

{ "name":"John Johnson", "street":"Oslo West 555", "age":33, "phone":"555 1234567"} 

The line above is the EXACT PAGE SOURCE; it runs locally though, so I can't show you the page.

When in a variable, I try to send it to my application with this:

document.getElementById("X_Axis").value=stuff.name;

through the input:

<input type="text" id="X_Axis" />

I get a undefined value every time.

I tried hardcoding the value in the JavaScript and it works fine like that, put when the embedded Ruby is put into the JavaScript variable, it always gives me the undefined value.

Share Improve this question edited May 9, 2012 at 23:24 the Tin Man 161k44 gold badges221 silver badges306 bronze badges asked May 9, 2012 at 22:12 ZippieZippie 6,0886 gold badges34 silver badges46 bronze badges 2
  • is X_Axis available to the DOM @ the time you call your function ? – Brandt Solovij Commented May 9, 2012 at 22:17
  • Yes, I have tried hardcodeing it in the same place as where i transfer the erb to js and it works. My money is on the qoutation marks of the embeded part while transfering it to js, but i have to find out how to remove the qoutation marks with a regex. Although, it won't work without them while transfering – Zippie Commented May 9, 2012 at 22:20
Add a ment  | 

1 Answer 1

Reset to default 4

You shouldn't be putting quotes around your ERB code, otherwise it puts the results in a string instead of assigning it to stuff as a hash/JSON object. Remove them and it should work. (Also, <% should be <%=).

var stuff = <%= Representative.get('http://0.0.0.0:4568/') %>;
发布评论

评论列表(0)

  1. 暂无评论