如何將此結果轉換為 javascript 陣列?
HTTP/1.1 200 OK 日期: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_jsonpilot”:[“ -api", "public_data"], "organization_name": "trustpilot", "developer.email": "dev.accounts [email protected]", "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", "refresh_count": "0", "status": "approved" }
我認為它會像 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);
}
})
uj5u.com熱心網友回復:
您需要在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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/321191.html
標籤:javascript php json 卷曲
上一篇:從郵遞員那里提取卷曲不起作用
