简体   繁体   English

如何从控制台中的js文件打印变量?

[英]How to print a variable from js file in console?

I am new to js and started using it with rails. 我是js的新手,并开始在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 console.log(var_name);' and it gets displayed in console window in browser window` ( ctrl + shift + j ) in firefox. console.log(var_name);' and it gets displayed in console window in在Firefox浏览器console.log(var_name);' and it gets displayed in console window inctrl + shift + j )。 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? 并且输出将显示在browser window/console或其他位置?

console.log(...) looks like JavaScript. console.log(...)看起来像JavaScript。 @customer looks like Ruby. @customer看起来像Ruby。 You can't print a Ruby variable in JavaScript - they execute at different times, in different environments. 您无法在JavaScript中打印Ruby变量-它们在不同的时间,不同的环境中执行。 If you're using an EJS file (not JS), then you can do 如果您使用的是EJS文件(而不是JS),则可以

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

which will insert the value of Ruby's @customer at the time the JS file is served; 它将在提供JS文件时插入Ruby的@customer的值; 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: 在几乎所有情况下,您都希望在HTML内呈现Ruby变量,或者通过使用AJAX请求将服务器变量的值传递给JavaScript代码,或者像这样在HTML内呈现:

<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 "" 您需要在“”或“”中插入红宝石代码

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

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