简体   繁体   English

红宝石代码中的Javascript变量

[英]Javascript variables in ruby code

In my RoR project I got html page, where I changing div's background image with javascript. 在我的RoR项目中,我得到了html页面,在这里我使用javascript更改了div的背景图像。 Javascript function send me index, and I want to use this index for getting element of ruby array. Javascript函数向我发送了索引,我想使用该索引来获取ruby数组的元素。

Look into my code 查看我的代码

function drawNewProject (index){
  console.log(<%= 'index' %>)
  <% index = 'index'  %>
  <% @existProjects = Admin::Project.order('weight') %>
  <% @existProject = @existProjects[index] %>

  var image = document.getElementById('block_one')

  image.style.backgroundImage="url('<%=  @existProject.image(:large) %>')";

}

But this line 但是这条线

<% @existProject = @existProjects[index] %>

Gives me error 给我错误

no implicit conversion of String into Integer

Do you know how to do it correct? 你知道该怎么做吗? Thnx. 谢谢

You have to think that the <%= erb %> block is executed in the server before being sent to the browser, and once there, the javascript is run. 您必须认为<%= erb %>块在发送到浏览器之前已在服务器中执行,并且一旦运行,就运行javascript。

Your browser has no idea about ruby or php or whatever... it just receives the html and the js (regardless is a static file, or a dynamically generated bunch of js) and runs it. 您的浏览器不知道ruby或php或其他任何内容……它只是接收html和js(无论是静态文件还是动态生成的js)并运行它。

That means that all the data must be known at rendering time. 这意味着必须在渲染时知道所有数据。 If your application depends on dynamic data, or on your user interaction, then you have to do an ajax request and deliver back a call with the right js to be run by the browser. 如果您的应用程序依赖于动态数据或用户交互,则必须执行ajax请求并使用正确的js传递回调用,以由浏览器运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM