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

Why is Javascript event handler changing my PHP variable?

我有一个网页 (page1.php) 表单可以发布到另一个带有访问登录表单的 PHP 页面 (page2.php)。我正在尝试将 2 个 $_POST 变量自动插入到访问登录表单中。 page2.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