OnReadyStateChange范围界定问题

OnReadyStateChange Scoping Issue

本文关键字:问题 范围 OnReadyStateChange      更新时间:2024-06-03

我正试图将New_Token函数中GetURL的值从函数中取出,以便使用它。我认为我的问题是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);
        }
    }
}

试试这个

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);
        }
    }
}