ApiToken
CallBack 関数からグローバル変数を設定できませんprocessGetToken
。理由を説明し、コードのサンプルを投稿していただけますか?
$(document).ready(function () {
// General Settings
var ApiToken, ApiUriGetToken, ApiUriGetPlaylist,
ApiSettings = {
clientId: encodeURIComponent('aaa'),
clientSecret: encodeURIComponent('bbb')
};
//-------------------------------------------------------------------------------------
// URIs to xxx API:
// Token
ApiUriGetToken = 'https://api.xxx.com/oauth/token?grant_type=client_credentials&client_id=' + ApiSettings.clientId + '&client_secret=' + ApiSettings.clientSecret;
//--------------------------------------------------------------------------------------
// Asynchronous requests using Ajax
// Get Token
function ApiGetToken() {
$.getJSON(ApiUriGetToken, processGetToken);
}
// Get Token : Callback
function processGetToken(data) {
ApiToken = data.access_token; // Set the Token as Global variable
// Update the URIs with the a Token generated
ApiUriGetPlaylist = 'https://api.xxx.com/playlist?oauth_token=' + ApiToken + '&account=' + ApiSettings.clientId;
}
//--------------------------------------------------------------------------------------
// Get Categories
function ApiGetPlaylist() {
ApiGetToken(); // Get a fresh Token
$.getJSON(ApiUriGetPlaylist, processGetCategories);
}
// Get Categories : Callback
function processGetCategories(data) {
var content = '';
// Trasvers
$.each(data.result, function (i, element) {
content += element.name;
});
// Inject in the DOM
$('#view01-caregories').text('ciao');
}
//--------------------------------------------------------------------------------------
// Testing
ApiGetToken();
console.log('ApiUriGetToken: ' + ApiUriGetToken);
console.log('ApiToken: ' + ApiToken);
});