简体   繁体   English

如何在不发布数据的情况下将数值从 PhP 传递到 Javascript?

[英]How to pass numeric values from PhP to Javascript without posting data?

I need some data from SQL to Javascript, so I called them in PhP and I'm trying to pass these values to Javascript, but the code below causes a NaN failure... if I set a PhP command for the Javascript variable, I can't use it as a numeric value... I need some data from SQL to Javascript, so I called them in PhP and I'm trying to pass these values to Javascript, but the code below causes a NaN failure... if I set a PhP command for the Javascript variable, I不能将其用作数值...

<?php
  $val=12;
?>
<script>
  var val="<?php echo $val; ?>";
</script>

I got a solution but I'm sure, this is not the best way to do this:我有一个解决方案,但我敢肯定,这不是最好的方法:

<?php
  $val=12;
?>
<input type="number" id="val" name="val" value="<?php echo $val; ?>" hidden>
<script>
  var val=getElementById('val').value;
</script>

One way of doing it is removing the quotes:一种方法是删除引号:

<script>
  var val = <?php echo $val; ?>;
</script>

But there may be edge cases in which php yields unexpected results, so in my opinion it's a good practice to keep the quotes and to update the value.但是可能存在 php 产生意外结果的极端情况,因此我认为保留引号并更新值是一个好习惯。

If you are sure that the value will always be an integer and/or that you need an integer in your code you can do:如果您确定该值将始终为 integer 和/或您的代码中需要 integer ,您可以执行以下操作:

var numericValue = parseInt(val, 10);

Or if you are using lodash:或者,如果您使用的是 lodash:

var numericValue = _.parseInt(val);

Remember to pass 10 as the second parameter which will specify the radix in the first case, as there may be edge cases in which numbers are interpreted with a base different than 10 (like hexadecimal or binary).请记住将 10 作为第二个参数传递,它将在第一种情况下指定基数,因为可能存在一些极端情况,其中数字以不同于 10 的基数解释(如十六进制或二进制)。

Otherwise if the value can be a float I suggest to do:否则,如果该值可以是浮点数,我建议这样做:

var numericValue = parseFloat(val);

And if you want to limit the digits after the decimal point you can do:如果你想限制小数点后的数字,你可以这样做:

var numericValue = Number(parseFloat(val).toFixed(4));

.toFixed() returns a string so if you still need a number it's better to convert it back to a number with the Number() function. .toFixed()返回一个字符串,因此如果您仍然需要一个数字,最好使用Number() function 将其转换回一个数字。

Passing the value through an input may work but it doesn't look like a good practice, anyway to get the element you will need to add document before getElementById :通过输入传递值可能有效,但它看起来不是一个好习惯,无论如何要获取您需要在getElementById之前添加document的元素:

var val = document.getElementById('val').value;

Thank you all, It's easier, then I thought, I thought?谢谢大家,这更容易,然后我想,我想? quotes are always needed.总是需要引号。 as JavaScript identify "<?php" tag as string.作为 JavaScript 将“<?php”标签标识为字符串。

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

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