Ruby on rails: using javascript variable in <&#

2019-04-26 16:48发布

问题:

I am trying to use insert an Javascript variable in the <%= %> tags but it prints the variable name verbose. Here is my code

<script>
     function getGraph(agency,device_id)
      {
            var i = document.createElement('img'); 
            i.src = '<%= show_graph_hcfcd_url('device_id') %>'; 
            $(graphDiv).appendChild(i); 
      }
</script>

Now the Problem is URL gets generated just fine except instead of value of device_id, 'device_id' appears in the rest url.

Any clues how to get over this?

回答1:

<%= %> will interpret the code on the server

and javascript variable is available to change on the client. So doing

<%= show_graph_hcfcd_url('device_id') %>

is probably not be the correct way of doing this.

You might want to try to put the url(s) in the data attibute of the element:

<div id="device_id" data-url="<%= show_graph_hcfcd_url(@device.id) %>">...</div>

<script>
     function getGraph(agency,device_id)
      {
            var i = document.createElement('img'); 
            i.src = $(device_id).data("url"); 
            $(graphDiv).appendChild(i); 
      }
</script>

also see

http://railscasts.com/episodes/324-passing-data-to-javascript

There's a good gem to do this called "gon"



回答2:

Here is how i have solved this for now:

<script>
     function getGraph(agency,device_id)
      {

            var i = document.createElement('img'); 
            var url = '<%= show_graph_hcfcd_url('device_id') %>'; //new change
            url = url.replace('device_id',""+(device_id*1000));   //new change
            i.src = url;
            $(graphDiv).innerHTML = "";
            $(graphDiv).appendChild(i); 
      }
  </script>

The lines in the bold show what i did. Basically replaced the "device_id" in the url with its value.

But I am still hoping for a more elegant solution.