【发布时间】: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