【问题标题】:How to declare response parameters of a server to string?如何将服务器的响应参数声明为字符串?
【发布时间】:2022-01-12 05:58:19
【问题描述】:

我一直在使用从 wordpress 自定义插件调用它的 API。我需要的响应参数之一是 Uid,它是一个长整数

这是我在 postmon 上得到的,什么是正确的,我也需要在 php 上得到这个值

但是当我尝试在 php 上打印相同的响应时,它会以某种方式舍入数字??

这是我在 php 方面得到的错误!

我正在使用 wordpress 中的 wp_remote_post 方法。我在想是否有办法手动将该 Uid 分配给字符串而不是整数以避免四舍五入。

我的代码:

    // Create new endpoint to get all products Data
add_action('rest_api_init', 'eos_store_rest_ajax_endpoint');

function eos_store_rest_ajax_endpoint()
{
    register_rest_route(
        'eos-store',
        'products',
        [
            'methods'               => 'GET',
            'permission_callback'   => '__return_true',
            'callback'              => 'eos_store_rest_ajax_callback'
        ]
    );
}

function eos_store_rest_ajax_callback()
{
    $url = "https://host:port/pospal-api2/openapi/v1/productOpenApi/queryProductPages";
    $response = wp_remote_post(
        $url,
        array(
    'method' => 'POST',
    'headers' => array(
        'data-signature' => 'DATA-Signature',
        'time-stamp' => '1641903969',
        'Content-Type' => 'application/json;charset=UTF-8'
    ),
    'body' => json_encode(array( 'appId' => 'APPID' )),
    'cookies' => array()
    )
    );

    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();
    
        return  "Something went wrong: $error_message";
    } else {
        return $response
    }
}

【问题讨论】:

  • 它不会自动改变。分享你的代码。
  • 请访问help center,使用tour查看内容和How to Ask。做一些研究,搜索关于SO的相关主题;如果您遇到困难,请发布您尝试的minimal reproducible example,注意输入和预期输出,最好在Stacksnippet
  • 我已经编辑了问题并添加了我的代码示例
  • 当 JSON 中的整数值超出 PHP 整数范围时,它将自动转换为浮点数,此时您会失去精度。 JSON_BIGINT_AS_STRING 标志必须在 json_decode 调用中设置(无论实际发生的位置),以将它们视为字符串值。
  • 其实问题不在于 php 端,它实际上是在解析 json 响应体时来自 Javascript。由于 Javascript 通常不支持大整数,并且在从 json 解析大整数时会丢失其精度。

标签: javascript php wordpress api


【解决方案1】:

其实问题不在于 php 端,它实际上是在解析 json 响应体时来自 Javascript。由于 Javascript 通常不支持大整数,并且在从 json 解析大整数时会丢失其精度。

关于这个 StackOverFlow 问题的已接受答案帮助我临时解决了我的问题。 https://stackoverflow.com/a/20408845/13858082

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 2022-08-15
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多