将大表单数字从 JavaScript 转换为字符串

convert large form number to string from javascript

本文关键字:转换 字符串 JavaScript 表单 数字      更新时间:2023-09-26

我有一个在 DB2 tech_id上执行查找的表单。tech_id是一个 26 位数字。我想通过 ajax 将其作为字符串传递给我的后端进程,但每次转换时:

2.015052714252E+25

这会破坏后端代码。

我以为通过使用toString功能,我会解决这个问题,但没有运气。这是jquery部分:

$('form').submit(function(event) {
var id = $('#tech_id').val().toString(); // the form input with the tech_id
$.ajax({
    type: 'POST',
    url: 'do_stuff',
    data: {id: id}, // also tried data: {id: id.toString()} here
    dataType: 'json',
    encode: true
})

然后在后端,我像这样传递它,再次尝试转换为字符串:

    $techid = $content['id']; // from the PHP $_POST array
    $host = 'my_API_endpoint'; 
    $url = $host."/user/".$techid;
    $results = file_get_contents((string) $url);

我不断收到以下错误:

file_get_contents(http:my_api_endpoint/user/2.015052714252E+25): failed to open stream: HTTP request failed! HTTP'/1.0 500 Internal Server Error

知道有什么问题吗?

编辑:我已将其缩小到控制器中的表单处理程序,它会自动json_decodes所有输入。转换字符串的是json_decode函数(在 php 中(。

JavaScript 没有 BigInteger 类型,因此它转换为指数形式。基本上,为了处理此类情况,人们使用了很多技术。

也有很多库来处理这个问题。 比如BigInt,BigNumber等,

但是对于您的情况,据我了解,我建议尝试将 26 位数字转换为十六进制并将其发送到后端。在后端再次将其从十六进制转换回整数。

我的意思是尝试使用这个

 $('form').submit(function(event) {
    var id = $('#tech_id').val().toString(16); // this converts to hexa
 $.ajax({
     type: 'POST',
     url: 'do_stuff',
     data: {id: id}, // this will be a String in hexa format.
     dataType: 'json',
     encode: true
})
$('form').submit(function(event) {
    var id = ""+$('#tech_id').val();
 $.ajax({
     type: 'POST',
     url: 'do_stuff',
     data: {id: id},
     dataType: 'json',
     encode: true
})

然后在查询时将其转换为数字或无需将其转换为数字,您可以将其保留为字符串没有问题

像这样使用url_encode。

 $url = $host."/user/".$techid;
 $url=  url_encode($url);

现在使用文件获取内容可能有帮助