简体   繁体   中英

How to print a variable from js file in console?

I am new to js and started using it with rails. I want to check what variable value is getting passed. I looked on internet and found the we have to use console.log(var_name);' and it gets displayed in console window in console.log(var_name);' and it gets displayed in console window in browser window` ( ctrl + shift + j ) in firefox. But when checked, nothing is displayed. Below is my code:

customer.js.erb file

console.log(@customer);

But the above is not displaying anything in the console.

Is it the right syntax? And the output is to be displayed in browser window/console or somewhere else?

console.log(...) looks like JavaScript. @customer looks like Ruby. You can't print a Ruby variable in JavaScript - they execute at different times, in different environments. If you're using an EJS file (not JS), then you can do

console.log(<%= @customer.to_json %>)

which will insert the value of Ruby's @customer at the time the JS file is served; but that is very likely not what you want. In almost all cases, you want to either render a Ruby variable inside the HTML, or else to communicate the value of the server variable to the JavaScript code by employing an AJAX request, or render it inside HTML like this:

<script>
  var customer = <%= @customer.to_json %>;
</script>

The right way is something like,

console.log("#{@customer.name}")

you need to interpolate ruby code in '' or ""

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