为什么 Javascript 事件处理程序会更改我的 PHP 变量


Why is Javascript event handler changing my PHP variable?

我有一个网页(page1.php)表单,它使用访问登录表单发布到另一个PHP页面(page2.php)。我正在尝试将 $_POST 变量中的 2 个自动插入到访问登录表单中。第 2 页.php 中的流程如下:

// assign the $_POST variables.
$number = $_POST['number'];
$accessCode = $_POST['accessCode'];
// quick check of the data type of $number
printf('Number: ' . $number . ' - ' . gettype($number) . ' data type <br />');
// The access login form...
printf('<form>');
printf('Number <input name="practiceNumber" id="practiceNumber" /><br />');
printf('Access Code <input name="practiceCode" id="practiceCode" />');
printf('</form><br /><br />');
//outside the </php ?> tags, the JavaScript to auto insert the values after 3 secs...
<script type="text/javascript">
var myVar=setInterval(function () {myTimer()}, 3000);
function myTimer() {
document.getElementById("practiceNumber").value = <?php echo $number); ?>;
document.getElementById("practiceCode").value = <?php echo $accessCode; ?>;
}
</script>
</php
// quick check to see if the data type of $number has changed
printf('Number: ' . $number . ' - ' . gettype($number) . ' data type <br />');

浏览器输出将值插入到表单字段中,但将字符串$number"5021251000801111111"更改为"5021251000801111000"。

为什么在使用 JavaScript 插入值时,字符串$number"5021251000801111111"更改得太"5021251000801111000"?

5021251000801111111大于

JS可以精确表示的最大整数。因为失去了精度,所以你会得到5021251000801111000

> Number.MAX_SAFE_INTEGER
9007199254740991

请改用字符串

ECMAScript 中的数字在内部表示双精度浮点数。当值设置为 5021251000801111111 (十六进制0x45AF112E76D32C47) 时,将为其分配最接近的可表示双精度值,即 5021251000801111000 (0x45AF112E76D32BD8)。

如果您想在不诉诸字符串的情况下操作大量数字,则可以使用该库或任何类似的项目。

https://github.com/jtobey/javascript-bignum