简体   繁体   中英

Javascript variables in ruby code

In my RoR project I got html page, where I changing div's background image with javascript. Javascript function send me index, and I want to use this index for getting element of ruby array.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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