我试图让GetURL
函数中的New_Token
的值退出函数,以便我可以使用它。我认为我的问题是request.onreadystatechange
行(虽然我无法确定)。在函数之外未定义GetURL
。
var GetURL;
var request = new XMLHttpRequest();
var path="https://ops.epo.org/3.1/auth/accesstoken";
request.onreadystatechange= function() {New_Token(GetURL);};
var encodedData = window.btoa("key:secret"); //encode consumer key and secret key
request.open("POST", path, true);
request.setRequestHeader("Authorization", encodedData);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send('grant_type=client_credentials'); //send request to server, must include grant_type in payload or it won't work
alert(GetURL);
function New_Token(GetURL) {
if (request.readyState == "4") //Request finished and response is ready
{
if (request.status == "200") {
console.log(request.responseText);
var TheResponse = JSON.parse(request.responseText);
console.log(TheResponse);
var TokenValue = TheResponse.access_token;
console.log(TokenValue);
GetURL = ("?access_token=" + TokenValue);
console.log(GetURL); //this is the added string that needs to be concact. on to ALL OPS calls
return(GetURL);
}
else {
alert("Problem retrieving data");
console.log(request.responseText);
}
}
}
答案 0 :(得分:0)
试试这个
function New_Token(GetURL) {
if (request.readyState == 4 || request.readyState == "complete")
{
if (request.status == 200||request.status == 0) {
console.log(request.responseText);
var TheResponse = JSON.parse(request.responseText);
console.log(TheResponse);
var TokenValue = TheResponse.access_token;
console.log(TokenValue);
GetURL = ("?access_token=" + TokenValue);
console.log(GetURL); //this is the added string that needs to be concact. on to ALL OPS calls
return(GetURL);
}
else {
alert("Problem retrieving data");
console.log(request.responseText);
}
}
}