开发者

Ruby object in my JavaScript file

开发者 https://www.devze.com 2023-01-09 16:39 出处:网络
I have a R开发者_开发百科uby object and I want to use that object in JavaScript. I haven\'t seen that type of thing, but I want a Ruby object in my .js file.

I have a R开发者_开发百科uby object and I want to use that object in JavaScript. I haven't seen that type of thing, but I want a Ruby object in my .js file.

Is this possible? Thanks in advance


No, you can't use your Ruby objects in JavaScript. You can, however, request any data encoded with JSON or XML (even plain text or your own data format) from the server-side using AJAX.


You can only pass strings, json or xml. Though, you can do it without ajax.

# dynamic_data.js.erb

var js_data = <%= Time.now.to_s -%> 

# show.html.erb

render :partial => 'dynamic_data'

or

- content_for :head do
    = javascript_tag "var js_data = #{ Time.now.to_s };"


You can't use Ruby objects within JavaScript because Ruby code executes on the server and JavaScript executes within the client Web browser. However, you can execute Ruby code and then use the results within JavaScript as Mark illustrates in his answer to your question.

0

精彩评论

暂无评论...
验证码 换一张
取 消