【问题标题】:Convert string to javascript array calling AJAX php curl call将字符串转换为javascript数组调用AJAX php curl调用
【发布时间】:2021-11-23 16:18:19
【问题描述】:

如何将此结果转换为 javascript 数组?

HTTP/1.1 200 正常 日期:2021 年 10 月 2 日星期六 09:19:28 GMT 内容类型:应用程序/json 内容长度:796 连接:保持活动

{ “refresh_token_expires_in”:“7779999”, "refresh_token_status" : "已批准", "api_product_list" : "[trustpilot-client-api, public_data]", "app_enduser" : "APIID", “api_product_list_json”:[“trustpilot-client-api”,“public_data”], “组织名称”:“信任飞行员”, "developer.email" : "dev.accounts+developerapps@trustpilot.com", "token_type" : "BearerToken", “issued_at”:“1633166368319”, "client_id" : "CLIENTID", "access_token" : "ACCESSTOKEN", "refresh_token" : "TOKENNAME", "application_name" : "NAME6", “范围” : ””, “refresh_token_issued_at”:“1633166368319”, “expires_in”:“359999”, “刷新计数”:“0”, “状态”:“已批准” }

我认为它会像 PHP 编码一样简单,然后是使用 JSON.parse 的 Javascript,但我得到错误 Uncaught SyntaxError: Unexpected token H in JSON at position 0

PHP 代码:

$payload = http_build_query(array(
'grant_type' => 'password',
'username' => $username,
'password' => $password
));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken'); //Url
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: Basic ' .  base64_encode($apiKey . ':' . $secretKey),
    'Content-Type: application/x-www-form-urlencoded'
));

$content=curl_exec($ch);

if (curl_error($ch)) {
    $error_msg = curl_error($ch);
    echo json_encode($error_msg);
} else {
    
    echo json_encode($content);

}
curl_close($ch);

AJAX 代码:

$.ajax({
    type: "POST",
    url: "api-test-access-token.php",
        dataType: "JSON",
        
        success: function (response, textStatus, xhr) {

            var jsonData = JSON.parse(response);
            console.log(response);


        }
    })

【问题讨论】:

    标签: javascript php json curl


    【解决方案1】:

    您需要将上面的CURLOPT_HEADER 设置为false(或删除该行),因为它会将标头添加到curl_exec 的输出中,当然这不是有效的JSON。 $content 将只包含响应的正文。

    来自 PHP 文档(参见 https://www.php.net/manual/en/function.curl-setopt.php):

    CURLOPT_HEADER  |  true to include the header in the output.
    

    【讨论】:

    • 谢谢,效果很好。你不会相信我已经用这个尝试不同的东西多久了 - 非常感谢! StackOverflow 应该有这个选项,所以我可以给你买啤酒!!
    • 很高兴听到!请将此答案标记为accepted,以帮助其他人更快地找到解决方案。
    • 全部完成,必须等待 3 分钟才能触发。
    猜你喜欢
    • 2017-01-04
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 2018-06-19
    • 1970-01-01
    相关资源
    最近更新 更多