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

时间:2015-01-24 04:36:51

标签: javascript php dom

我有一个网页(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&#39; 5021251000801111111&#39;到&#39; 5021251000801111000&#39;。

为什么字符串为$ number&#39; 5021251000801111111&#39;也改变了&#39; 5021251000801111000&#39;何时使用JavaScript插入值?

2 个答案:

答案 0 :(得分:2)

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

> Number.MAX_SAFE_INTEGER
9007199254740991

改为使用字符串

答案 1 :(得分:2)

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

如果你想操纵大数字而不求助于字符串,你可以使用那个库或任何类似的项目。

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