我无法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);
});