将字符串转换为javascript数组,调用AJAX php curl调用



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

HTTP://1.1 200 OK日期:2021年10月2日星期六09:19:28 GMT内容类型:application/json内容长度:796连接:保持有效

{"refresh_toke_expires_in":"77779999";,"refresh_toke_status":"批准";,"api_product_list":"[trustpilot客户端api,public_data]";,"app_enduser":"APIID";,"api_product_list_json":["trustpilot客户端api"、"public_data"],"organization_name":"trustpilot";,"developer.email":"dev.accounts+developerapps@trustpilot.com&";,"token_type":"BearerToken";,"issued_at":"1633166368319";,"client_id":"CLIENTED";,"access_token":"ACCESSTOKEN";,"refresh_token":"TOKENNAME";,"application_name":"NAME6";,"范围":";,"refresh_token_issued_at":"1633166368319";,"expires_in":"359999";,"refresh_count":"0";,"状态":"批准";}

我原以为它会像PHP编码它一样简单,然后是使用JSON.parse的Javascript,但后来我得到了错误Uncaught SyntaxError:JSON中位于位置0的意外令牌H

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);

}
})

您需要将上面的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.

最新更新